Master Optional Chaining and Nullish Coalescing in JavaScript
Write Safer and Cleaner Code with Optional Chaining and Nullish Coalescing
JavaScript has a feature for almost every problem you have. One of the recent features that can make your code cleaner is the optional chaining (?.) and nullish coalescing (??)
Suppose you are working with an API that returns an object with deeply nested properties, the optional chaining (?) feature helps you to access the property without worrying if it exists.
For example, suppose you have an object like this:
const user = { profile: { name: 'Alice' } };
If you try to access a property which doesnβt exist directly , it will cause an error.
Using Optional Chaining
To solve this issue, you can use optional chaining to short circuit the evaluation of the referenced property to null or undefined.
The syntax looks like this:
obj.val?.prop
obj.val?.[expr]
obj.func?.(args)
We know that errors can cause programs to stop executing. To prevent errors from stopping your program altogether, optional chaining returns undefined if the referenced property is not found.
Here is how itβs done.
Nullish Coalescing (??)
You might be wondering, why return undefined
at all? It's not always ideal, especially when you expect a meaningful value. This is where the Nullish Coalescing operator (??
) comes in. It allows you to define a fallback value if the original one is null
or undefined
.
For example, using our user
object from earlier, if the user doesnβt have an address, we can return a custom value instead:
All we need to add is ??
at the end of the optional chaining and supply the custom value as shown below.
In our case, if the address property doesnβt exist, the default value will be βNo address provided'β
Ready to dive into React?
This is so similar to C#