Javascript developing tips, you need to know!

Javascript developing tips, you need to know!

·

2 min read

TypeError: cannot read property 'xyz' of undefined

As someone who handles the front-end, I bet this thing frustrates you. As a long response from the API goes, there will be a time where the response you are supposed to get is just not there, whether it's due to lack of data or typo it's still annoying to get that revision call on the weekend.

this fix called, Optional Chaining this feature is used to check if the object you want is available or not. Available? show it, Nah? return undefined. This is better than getting an error message.

carbon.png

Generate view using js

If you ever learn react.js you'll be similar with a component, this topic is called Micro frontend where each part of the page is its own component that is then being assembled into a complete UI. I work a lot with multiple similar components such as Modal. And having multiple Modal Bootstrap codes in HTML files will look crumpled. I learn this from my senior, what he was doing is creating a component file, then call it once on every page that needs a simple modal,

and we just customize the change using javascript: "document.getElementById("div-hello").innerHTML = "Hello There!";"

or in jquery: $('#div-hello').html("Hello There!").

For me the benefit of using this method is :

  • less cluttered HTML file,
  • no need for clearing the form,
  • you can directly put out response into the HTML without worrying about id/class/name

Creating my own simple plugins

Depending on how data is displayed on JSON response, the one that is tricky for me is always type date. There are some plugins like moment.js that handle it, but sometimes we need a quicker fix, and that is when I realize that it's easier to just make my own. Usually, when we get a JSON response, we get the value as type "string"(CMIIW), and so I usually handle it as a string.

here is an example:

carbon (1).png

Hope this helps!

These 3 tips really help me create a better code in my earlier days, although this is helpful it will always come back to preference. Hope this post helps you!

More like this? visit my hashnode