Javascript destructuring vs optional chaining and nullish coalescing operator
Javascript was designed to be the glue between HTML and CSS and nothing more. Before ES6 in 2015, the language was pretty much dormant for 6 long years. Today, it is arguably one of the most used language with new features been released every year. Destructing, optional chaining and nullish coalescing have made our developer life so much easier. Let’s have a look at them.
What is destructuring ?
It allows the Javascript expression to retrieved values from objects or arrays, into unique variables.
Below is a sample code that we will be looking at. We have an employee
object that contains information — a typical api response 🙂.
At line 14, we are destructuring the employe
to retrieve firstName, lastName, city and the second hobby
This is what being outputted. Its clear simple, clean and easy to understand codes 🙂
But destructuring has a hidden behaviour that most junior developers will not know. In a real production application, errors happen and need to be handled properly to provide a good user experience to customers.
This is what happens when we comment out address property. Not good right ? 🥲
We can fix this by setting a default value — address: { city } = {}
to address when destructuring occur.
Now the application does not crash and city is not printed out because its value will be undefined
in this case.
Here is the catch when setting default value. Set firstName to null
and a default value of firstName to John when destructuring.
As you can see null
value is printed out 😩 instead of our default value John which means only undefined
is replaced.
What is optional chaining and nullish coalescing operator ?
The optional chaining operator is represented as
?.
and it behaves exactly the same as.
chaining operator but returnundefined
when it fails.
Comment out the property hobbies and update the code to use optional chaining
In this case, undefined
is outputted for secondHobby. But we don’t want undefined
to be printed out but rather a default value. We can achieve this by using the nullish coalescing operator ??
It is a logical operator that returns its right-hand side operand when its left-hand side operand is
null
orundefined
, and otherwise returns its left-hand side operand.
Let’s try it. Set firstName to null
and use nullish coalescing operator for firstName and secondHobby.
This is better now since we have default values being outputted when either null
or undefined
is encountered.
Conclusion
As you can see, its not a battle between destructuring vs optional chaining and nullish coalescing operator but rather how you want to handle null
and undefined
values. So ask yourself first how to deal with them. You can also mix and match them together to make your code more readable 🙂