In this article, we will learn about the double question mark operator i.e the nullish coalescing operator in Javascript.
While working or reviewing codes on Github, we sometimes come across the ??
sign in some conditional statements.
This double question mark (??
) operator is called the nullish coalescing operator.
What is a nullish coalescing Operator (??)
The nullish coalescing (??) operator was introduced in Javascript2020. It is a logical operator that returns the value of the right-hand side when the value of the left-hand side is null
and undefined
.
Syntax:
leftExpr ?? rightExpr
Example:
const user1 = null;
const user2 = undefined;
console.log(user1 ?? 'no user') // no user
console.log(user2 ?? 'no user') // no user
In the above example, we have assigned user1 and user2 as null
and undefined
.
And since user1
and user2
are null and undefined, the operator returns the value of the right-hand side of the mark i.e ‘no user’.
The common use of the ??
operator is to give a default value. For example
let user;
console.log(user ?? 'Max') // Max
Since the variable user is undefined
, the ??
operator returns Max as the output.
Now, let’s define a value for the user variable and check what it returns.
let user = 'Jack'
console.log(user ?? 'Max') // Jack
Since the left side value is not undefined/null
, it returns the value on the left-side of the mark. i.e Jack.
We can also get the same result using the OR ||
operator too.
let user = 'Jack'
console.log(user || 'Max') // Jack
However, there are differences between the ||
(OR) operator and the ??
operator.
Difference between the ||
(OR) operator and the ??
nullish coalescing operator
The main difference between the Javascript OR (||
) and the nullish coalescing operator is that:
- The
??
operator does not replacefalsy
value for the right-side expression.
let user = ""
console.log(user ?? 'Max') // ""
An empty string is considered a false
value in Javascript.
The nullish coalescing operator only replaces the value with the right-side, when the left expression is null
or undefined
.
- The
||
(OR) operator considers0
,falsy
, an empty string (""
) and thenull/undefined
value as same. So it will replace the value with the right-side expression if the left-side value is afalsy
value.
let user = ""
console.log(user || 'Max') // Max
Since an empty string (""
) is a falsy value, so the value got replaced by the right-side using the ||
(OR) operator.
Conclusion:
The Javascript double question mark operator is a logical operator known as the nullish coalescing operator. It returns the right-side expression as the default value if the left-side values are null
or undefined
.
It works similarly to the OR
operator but the ??
operator does not return the right-side expression even when the left value is falsy
.
Other Articles You’ll Also Like:
What is memoization and how to cache function results in Javascript