Is there a null-coalescing (Elvis) operator or safe navigation operator in JavaScript?
For default values in null or undefined cases, use JavaScript's nullish coalescing operator (??):
For safely accessing nested properties, use JavaScript's optional chaining operator (?.):
A closer look at nullish vs falsy values
The ?? operator shines when distinguishing between nullish and falsy values. Nullish values are fewer - only null and undefined. However, Falsy drags more elements into the club:
nullundefinedfalse0''or""NaN
Crucially, ?? only defaults to its right-hand side for nullish values, while || will do so for all falsy values:
This matters if you're dealing with 0, false, and "" where you don't want the truthy default value to override falsy-but-legitimate values.
Safely navigating your way into nested property checks
Nested properties often feel like walking on a tightrope! You could plummet with errors if you don't tread carefully. For example:
In the old-school way without optional chaining, you might verify each "hop" like this:
But with the optional chaining operator, you can express the same idea much more concisely and readably:
Add in the nullish coalescing operator, and you've got a one-two punch for secure defaulting:
Dynamic properties: Safe checks, no exception wreck
When you're unaware of an object's full structure, trying to access non-existent properties may usher in exceptions. This situation can be handled by using optional chaining that defaults to undefined. Alternatively, when a null or undefined object crops up, step in with an empty object ({}) as a safeguard:
Think of the above pattern as a kind of safe navigation mechanism in JavaScript, shielding your code against NullPointerExceptions.
Old environments? Transpile everything
One caveat about optional chaining and nullish coalescing: these are modern JavaScript features and might not be supported in older environments, even some that are still in common use. @babel plugins come to the rescue, transforming your new syntax to a digestible version for older browsers:
@babel/plugin-proposal-optional-chaining@babel/plugin-proposal-nullish-coalescing-operator
By using these plugins, cutting-edge code can still run and shine in older platforms.
Was this article helpful?