Basics
Before we start, let's get the basic concepts out of the way.
There are 6 falsy values in JavaScript which are undefined
, null
, NaN
, 0
, ""
, false
.
These above values will be taken as a false
value in a condition. learn more
Introduction
We generally use logical OR (||
) operator to return the right operand if the left operand is falsy.
The syntax goes as leftExpression || rightExpression
If the leftExpression
is truthy, it will be returned.
If the leftExpression
is falsy, rightExpression
will be returned.
For example:
let falsyValue = 0;
let truthyValue = 1;
console.log(falsyValue || 'printed'); //output: 'printed'
console.log(truthyValue || 'nope'); //output: 1
This can lead to unexpected issues if you consider 0
or ""
(empty string) as valid values.
This is where Nullish Coalescing (??
) operator helps us. It was introduced in ES2020.
Nullish Coalescing (??)
Nullish Coalescing (??
) operator is used to return the right expression if left expression is nullish.
A nullish value is a value that is either
null
orundefined
.
Here are some examples of expressions:-
// comments represent the value returned
0 ?? 'expressionB' // 0
0 || 'expressionB' // expressionB
'' ?? 'expressionB' // ''
'' || 'expressionB' // expressionB
null ?? 'expressionB' // expressionB
null || 'expressionB' // expressionB
undefined ?? 'expressionB' // expressionB
undefined || 'expressionB' // expressionB
let object = {}; // same for [] as well
object ?? 'expressionB' // {}
object || 'expressionB' // {}
Short-Circuiting
Similar to AND (&&
) and OR (||
) operators, Nullish Coalescing (??
) is also short-circuited meaning it will not execute the right operand if the left operand is neither null
nor undefined
.
Chaining
Chaining ??
with &&
or ||
operator will throw a SyntaxError
null || undefined ?? 'OK'; // Uncaught SyntaxError: Unexpected token '??'
This can we avoided by using parentheses to explicitly specify the operator precedences
(null || undefined) ?? 'OK'; // "OK"
Top comments (0)