Nullish coalescing operator '??' Flashcards

1
Q

As it treats null and undefined similarly, we’ll use a special term here, in this article. We’ll say that an expression is “defined” when it’s neither null nor undefined.

A

The result of a ?? b is:

if a is defined, then a,
if a isn’t defined, then b.

In other words, ?? returns the first argument if it’s not null/undefined. Otherwise, the second one.

The nullish coalescing operator isn’t anything completely new. It’s just a nice syntax to get the first “defined” value of the two.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

For example, here we show user if defined, otherwise Anonymous:

A

let user;

alert(user ?? “Anonymous”); // Anonymous (user not defined)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

another example

A
let firstName = null;
let lastName = null;
let nickName = "Supercoder";
// shows the first defined value:
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Main Difference Between ?? or ||

A

The important difference between them is that:

|| returns the first truthy value.
?? returns the first defined value.

In other words, || doesn’t distinguish between false, 0, an empty string “” and null/undefined. They are all the same – falsy values. If any of these is the first argument of ||, then we’ll get the second argument as the result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Another example

A

In other words, || doesn’t distinguish between false, 0, an empty string “” and null/undefined. They are all the same – falsy values. If any of these is the first argument of ||, then we’ll get the second argument as the result.

In practice though, we may want to use default value only when the variable is null/undefined. That is, when the value is really unknown/not set.

For example, consider this:

let height = 0;

alert(height || 100); // 100
alert(height ?? 100); // 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Precedence

A

The precedence of the ?? operator is about the same as ||, just a bit lower. It equals 5 in the MDN table, while || is 6.

That means that, just like ||, the nullish coalescing operator ?? is evaluated before = and ?, but after most other operations, such as +, *.

So if we’d like to choose a value with ?? in an expression with other operators, consider adding parentheses:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly