Nullish coalescing operator (??)
Examples
let userName = null
// If userName is null or undefined, use 'Guest' as the default value.
// Otherwise, use the value of userName.
let displayName = userName ?? 'Guest'
console.log(displayName) // Outputs 'Guest'
let count = 0
// If count is null or undefined, use 1 as the default value.
// Otherwise, use the value of count.
let increment = count ?? 1
console.log(increment) // Outputs 1
let message = ''
// If message is null or undefined, use 'Hello, world!' as the default value.
// Otherwise, use the value of message.
let greeting = message ?? 'Hello, world!'
console.log(greeting) // Outputs 'Hello, world!'
Syntax
The syntax for the nullish coalescing operator is as follows:
expression1 ?? expression2
The left-hand operand (expression1) is evaluated first. If it is null or undefined, the right-hand operand (expression2) is returned. Otherwise, the left-hand operand is returned.
Description
The nullish coalescing operator is a logical operator that is used to provide a default value for a variable that may be null or undefined.
It is similar to the logical OR operator (||), but the nullish coalescing operator only returns the right-hand operand if the left-hand operand is null or undefined, whereas the logical OR operator returns the right-hand operand if the left-hand operand is any falsy value (i.e., a value that is considered false when evaluated in a boolean context).
Specifications
The nullish coalescing operator is specified in the ECMAScript 2020 (ES2020) language specification.
Browser Compatibility
- Google Chrome (version 80 and later)
- Microsoft Edge (version 84 and later)
- Mozilla Firefox (version 74 and later)
- Safari (version 14 and later)
Similar Operators
There are several other operators in JavaScript that are similar to the nullish coalescing operator, including:
- The logical OR operator (||): This operator returns the right-hand operand if the left-hand operand is any falsy value (i.e., a value that is considered false when evaluated in a boolean context).
- The ternary operator (?:): This operator is a conditional operator that allows you to specify a default value for a variable based on a condition. It has the following syntax:
expression1
?expression2
:expression3
. Ifexpression1
is truthy, the operator returns expression2. Ifexpression1
is falsy, the operator returnsexpression3
.