In this post, I’ll explain about two of the recent additions to the javascript. Nullish Coalescing
and Optional Chaining
.
Nullish Coalescing
When accessing a property of a object in javascript, we usually provide a fallback value incase the property is not present (undefined
) or null
.
For Example. Consider a object like this
The usual way for this handle fallback is by using the ||
operator
The first two examples work as we expected, but for other cases we get the result as right hand side value of ||
operator as shown in the above example.This is because the values on left hand side already evaluate to falsy
in Javascript.
For this problem, we use the Nullish Coalescing
operator
Once we switch to nullish coalescing operator, we get the expected results.
Optional Chaining
When accessing a nested property in the object, we usually have to check whether intermediate properties are present.
For Example, Consider a object with nested properties like this
Since, we are accessing nested values, if address
is undefined we get an error like Cannot read property home of undefined
. In this case, we use Optional Chaining
operator.
To use the optional chaining operator, we have to put a ?
before accessing a property. So above example changes to this
Combining both of them
Although these both operators are good seperately, when combined they become very useful. I can take the sample example and nullish coalescing operator at the end of it.