Cool Javascript tricks to reduce your code.

Clive Mac
3 min readAug 4, 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

console.log(parent && parent.child1 && parent.child1.child2 && parent.child1.child2.child3 && parent.child1.child2.child3.child4)

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. [Source : MDN ]

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

optionalNumber === null || optionalNumber === undefined

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. [Source : MDN ]

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. [ Source: MDN ]

The youtube channel Web Dev Simplified also has has a cool video about these features you can take a look at [Link: Web Dev Simplified]

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

--

--

Clive Mac

Hello World 👋 I’m currently working as a Frontend Developer. 🔭 Based in Munich, Germany. 🌍 Mostly codes in JavaScript and React.js. 🛠