Unknown and very useful JS operators

In any programming language, one of the most important things is to have a clean code that can be read by anyone. And, if you can delete some lines and make it sorter, even better! In Spain we have an old saying: «lo bueno si es breve, dos veces bueno» (The good, if it is brief, twice good). Although whoever invented this saying I don’t think he was thinking about programming, it also works for us.

To carry out this fact, I teach you three very useful JS operators that we don’t use a lot and many people don’t know them.

  1. ?? or «nullish coalescing operator»

This operator is passed 2 values. If the first value is null or undefined, it returns the second. If first value isn’t null or undefined, it returns the first and second value won’t be evaluated:

|| (OR) operator is very similar, but the difference is that if you use OR operator to put values by default to a variable, it doesn’t accept ’ ’, 0 or false. So we can say that:

  • || returns the fisrt truthy value
  • ?? retuns the first defined value
Nullish coalescing operator

An interesting thing is that you can use OR and ?? together, but you have to use parenthesis:

2. ??= «nullish assignment operator»

This operator is the opposite: only assigns if the left side variable is nullish (if it’s undefined or null).

Nullish assignment operator

Now that we know the nullish coalescing operator we can see that this is the same:

3. ?. «optional chaining operator»

This operator allows us to read the values of the properties inside objects, without having to validate one by one. If any reference is null, it returns undefined.

If you don’t use this operator and call a null reference, you will have an error and execution of all code will stop.

Optional chaining operator

You can use optional chaining operator with:

  • object?.porperty => person?.firstName
  • object?.[expresion] => object?.[i++]
  • array?.[index] => array?.[3]
  • object.method?.() => person.sayHello?.()

I’m sure many of you already knew these operators, but for those who don’t, I hope they help you!

Junior frontend developer