Coding in Javascript made easy

Nihal Khan
3 min readDec 6, 2021

I have some cool Javascript tricks that I believe when used extensively throughout your code will help reduce your file size and will be easier to read for you colleagues. Hopefully you find them useful.

1. Avoid verifying objects like this

It looks ugly. Instead if the object is expected to be nested; use it like this:

The ?. operator is known as Optional chaining. This also works on arrays.

Avoid writing an array like the following,

Instead write it with this

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

2. Avoid verifying null and undefined with the `OR (||)` operator when numbers are involved like this

in a code like this,

If you have a function and you want to avoid writing code to verify the difference between null, undefined and 0. Because javascript considers 0 as false. You need to do something like this,

the ?? operator is known as Nullish coalescing operator. It will only check for null or undefined on the left hand of the operator.

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

3. Avoid writing the script tag below body tag.

Instead use the defer keyword with the script tag and add it in the head tag like this

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.

That’s all for now, hope you like these tricks and use it everyday for cool things in Javascript.

--

--

Nihal Khan

I’m predominantly a JavaScript developer with 11+ years of development experience in building software with Node, React Native, ReactJs , Angular and OOJS .