In Javascript, the nullish coalescing operator, or ??
operator is used to return the right hand side whenever the left hand side is null
or undefined
. To understand a little bit better, let's look at a few examples:
// Is set to 0
let x = 0 ?? "hello";
// Is set to goodbye
let y = undefined ?? "goodbye";
// Is set to hello
let z = null ?? "hello";
// Is set to false
let a = false ?? "goodbye";
The nullish coalescing operator is useful in situations where something can be returned as either null
or undefined
, and helps us tighten up our code. For example, a function that returns undefined in some situations can be provided with a default value:
let myFunction = (a) => {
if(a >= 5) {
return "hello world";
}
}
// Will return "goodbye world", since `myFunction(4)` returns undefined.
let runFunction = myFunction(4) ?? "goodbye world";
Differences between the logical OR operator
In the past, we typically set default values in Javascript using the logical OR (||
) operator. It has the same kind of functionality, in that it sets a value if the first value on the left doesn't meet certain criteria. However, the ||
operator returns the right hand value if the left hand value is anything falsy - and there are a lot of falsy values, as shown in the list below.
Falsy Values
-
false
-
0
or-0
or0n
- any empty string, i.e.
""
-
null
-
undefined
-
NaN
As such, using the ||
operator would mean that if a function returned the value 0
, and we really did want to use the 0
value, we wouldn't be able to - since 0
is falsy. With the nullish coalescing operator (??
), 0
is a valid value since it only triggers if a value is null
or undefined
:
// Is set to 0
let x = 0 ?? 5;
// Is set to 5
let y = 0 || 5;
Similarly, if a string is empty, the ||
operator would default to the right hand side - which is not always the desired behaviour. The ??
operator lets us avoid that:
// Is set to ""
let x = "" ?? "default text";
// Is set to "default text"
let x = "" || "default text";
Chaining the nullish coalescing operator
It is also possible to chain the nullish coalescing operator, as shown below:
// Is set to "default text"
let x = null ?? undefined ?? "default text";
But you cannot chain it with the logical ||
operator, unless with parenthesis:
// Errors out:
let x = 0 || undefined ?? "default text";
// Returns "default text";
let y = (0 || undefined) ?? "default text";
Comments (0)