ES11 has added a nullish coalescing operator which is denoted by double question marks, like this:
In this article, we will explore why it’s so useful and how to use it.
Let’s get started.
The || operator returns the first
The following are the
only six values that are considered to be
- “”(empty string)
So if anything is not in the above list, then it will be considered a
Falsy values are the non-boolean values that are coerced to
false when performing certain operations.
const value1 = 1; const value2 = 23; const result = value1 || value2; console.log(result); // 1
As the || operator returns the first
truthy value, in the above code, the
result will be the value stored in
value1 which is
empty or any other
falsy value, then the next operand after the || operator will be evaluated and that will the result of the total expression.
const value1 = 0; const value2 = 23; const value3 = "Hello"; const result = value1 || value2 || value3; console.log(result); // 23
value1 is 0,
value2 will be checked. As it’s a truthy value, the result of the entire expression will be the
The issue with the || operator is that it doesn’t distinguish between
0, an empty string
undefined. They all are considered as
If any of these is the first operand of || , then we’ll get the second operand as the result.
The || operator works great but sometimes we only want the next expression to be evaluated when the first operand is only either
Therefore, ES11 has added the nullish coalescing operator.
In the expression
x ?? y,
- If x is either
undefinedthen only result will be
- If x is not
undefinedthen the result will be
This will make the conditional checks and debugging code an easy task.
Try it yourself
let result = undefined ?? "Hello"; console.log(result); // Hello result = null ?? true; console.log(result); // true result = false ?? true; console.log(result); // false result = 45 ?? true; console.log(result); // 45 result = "" ?? true; console.log(result); // "" result = NaN ?? true; console.log(result); // NaN result = 4 > 5 ?? true; console.log(result); // false because 4 > 5 evaluates to false result = 4 < 5 ?? true; console.log(result); // true because 4 < 5 evaluates to true result = [1, 2, 3] ?? true; console.log(result); // [1, 2, 3]
So from all of the above examples, it’s clear that the result of the operation
x ?? y is
y only when
x is either
In all the other cases, the result of the operation will always be
As you have seen, the nullish coalescing operator is really useful when you only care about the
undefined value for any variable.
- ES6 Destructuring
- Import and Export Syntax
- Arrow functions
- Optional chaining operator
and a lot more.
Subscribe to my weekly newsletter to join 1000+ other subscribers to get amazing tips, tricks, articles and discount deals directly in your inbox.
Read More …