JS Coding Practices

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

  1. Stop checking array length using [ ].length > 0, rather [].length will also do the same inside any condition.

2. Prefer using boolean result wherever possible using !!

3. Conditionally add a property to an object

Have you ever wanted to add a property to a JavaScript object but only if some requirements are met?

If you encountered that situation, the code you may have produced could be very verbose as two if statements are required. However, a JavaScript trick exists that allows us to eliminate the additional statements we would have written.

Conditionally add a property to an object

Here it is! We are only adding the moreInfos property only when the variable value is different from undefined.

We are leveraging the spread syntax (…) to spread the object { moreInfos } and using the AND operator that permits us to return the second value of the condition when the first is evaluated to true.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anil Kumar

Anil Kumar

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.