Member-only story
Why Is the Nullish Coalescing Operator(??) Essential in JavaScript?
Smarter Coding Starts Here
As JavaScript developers, we've all been there - having to check if a variable is null
or undefined
before using it. This results in a lot of repetitive conditional checks that can clutter up our code.
With the introduction of the nullish coalescing operator in ECMAScript 2020, we have a cleaner way to handle null
or undefined
values.
In this post, I'll explain what the nullish coalescing operator is, demonstrate how to use it, and discuss why it's such an essential addition to the JavaScript language.
What is the Nullish Coalescing Operator?
The Nullish Coalescing Operator (??) is a logical operator introduced in ECMAScript 2020 to handle default values for null
or undefined
.
It returns the first operand if it’s not
null
orundefined
. Otherwise, it returns the second operand.
The basic syntax looks like this:
let name = value ?? 'Default';
If value
is null
or undefined
, it will return 'Default'
. If value
has any other value such as '', 0, false, etc. it will return that value unchanged.