Borislav Hadzhiev
Thu Mar 17 2022·2 min read
Photo by Will Truettner
Use the nullish coalescing operator (??) to set a default value if undefined
in TypeScript, e.g. const result = country ?? 'Germany'
. The nullish
coalescing operator returns its right-hand side operand when the value to the
left is undefined
or null
.
let country: string | undefined; const result1 = country ?? 'Germany'; console.log(result1); // 👉️ "Germany"
An easy way to think about the
nullish coalescing operator (??)
is that it allows us to provide a fallback value if the value to the left is
equal to undefined
or null
.
If the value to the left is not undefined
or null
, the operator returns the
value as is.
const result1 = 'hello' ?? 'Germany'; console.log(result1); // 👉️ "hello"
An alternative approach is to explicitly check whether the value is equal to
undefined
with a ternary operator.
let country: string | undefined; const result2 = country === undefined ? 'Belgium' : country; console.log(result2); // 👉️ "Belgium"
The ternary operator returns the value to the left of the colon if the expression to the left of the question mark is truthy, otherwise the value to the right of the colon is returned.
country
variable stores an undefined
value, the ternary operator returns Belgium
, otherwise we return the value stored in the country
variable.Notice that we used the strict equality operator (===). You might also see examples online that use loose equality (==).
const result2 = country == undefined ? 'Belgium' : country; console.log(result2); // 👉️ "Belgium"
The difference between the examples above is that the loose equality (==)
operator checks for both null
and undefined
, whereas strict equality (===)
checks only for the specific value (undefined
in the example).
An easy way to visualize this is to use the operators to compare undefined
and
null
.
console.log(undefined == null); // 👉️ true console.log(undefined === null); // 👉️ false
The example shows that when using the loose equality operator (==), undefined
is equal to null
.
You can also use the logical OR (||) operator to provide a default value if a
variable stores an undefined
value.
let country: string | undefined; const result3 = country || 'Denmark'; console.log(result3); // 👉️ "Denmark"
The logical OR (||) operator returns the value to the right if the value to the left is falsy.
undefined
or null
.The falsy values in JavaScript (and TypeScript) are undefined
, null
, 0
,
false
, ""
(empty string), NaN
(not a number).
This means that the logical OR (||) operator will return the value to the right if the value to the left is any of the aforementioned 6 falsy values.
On the other hand, the nullish coalescing operator will return the value to the
right only if the value to the left is undefined
or null
.