??) as in the code below:
alert(username ?? "Guest");
The nullish coalescing operator simply returns the expression on the right-side of the mark when the expression on the left side is
For example, the following code will assign the
firstName variable value as the value of
username variable. When the
firstName value is null, the
username will be assigned as
let firstName = null; let username = firstName ?? "Guest"; console.log(username); // "Guest"
Or you can also write it this way:
let username = undefined ?? "Guest"; console.log(username); // "Guest"
||) the nullish coalescing operator won’t replace
false values with the right-side expression. One example of this is when you pass an empty string (
"") as the left side expression.
false as in the code below:
The nullish coalescing operator was created because there will be times when you want to consider falsy values like
0 and empty string
"" to be valid values. The use of OR operator will prevent you from returning any falsy values.
By using the nullish coalescing operator, you will only replace exactly
undefined values with a defined value.
Using ?? with || and && operators
||) and AND (
&&) operators without a parentheses
() separating the operators.
For example, the following code tries to see if either
lastName variable can be used as the value of
username before using
"Guest" as its value:
let firstName = "John"; let lastName = "Stone"; let username = firstName || lastName ?? "Guest"; // Error: Unexpected token '??' console.log(username);
The following code will first evaluate the expressions inside the parentheses:
let firstName = null; let lastName = undefined; let username = (firstName || lastName) ?? "Guest"; // Error: Unexpected token '??' console.log(username); // "Guest"
And that’s how you combine the nullish coalescing operator with either AND or OR operator.
Unlike the OR operator, the nullish coalescing operator is a situational operator that allows you to return
0 and empty string
"" as a valid value for your application.
Don’t forget to use a parentheses when you combine it with AND / OR operator 😉