The nullish coalescing operator is a logical operator that returns its right-hand operand when its left-hand operand is null
or undefined
, and otherwise returns its left-hand operand.
Syntax
Usage
The nullish coalescing operator is useful for providing default values while distinguishing between null
/undefined
and other falsy values (like 0
, ""
, false
, etc.). This is particularly helpful in situations where we want to avoid mistakenly treating other falsy values as needing the default.
Notes on Truthy and Falsy Values in JS
Detailed Examples
Providing Default Values
In the given example:
This means:
- If
config.timeout
isnull
orundefined
,timeout
will be assigned the value3000
. - If
config.timeout
is any other value (including0
,false
,""
, etc.), timeout will be assigned the value ofconfig.timeout
.
Nullish Coalescing with null
and undefined
Nullish Coalescing with Other Falsy Values
Comparison with Logical OR (||
)
The logical OR (||
) operator can also be used to provide default values, but it treats all falsy values (like 0
, false
, ""
, etc.) as needing the default, not just null or undefined.
Further details on Short Circuiting in JS
Example
Summary
- Nullish Coalescing Operator (
??
): Used to provide a default value when the left-hand operand isnull
orundefined
. - Syntax:
const result = value ?? defaultValue;
- Purpose: Distinguishes between
null
/undefined
and other falsy values, providing a default only when necessary. - Comparison with
||
: The logical OR operator treats all falsy values as needing the default, while??
only considersnull
andundefined
.