Coding in Javascript made easy
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 isnull
orundefined
, 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 thedefer
attribute will prevent theDOMContentLoaded
event from firing until the script has loaded and finished evaluating.