Hello World, in my recent post, I wrote on JavaScript operators (Logical operators and Unary operators). In this post, I share insight on the nullish coalescing operator which is a recent addition to the language.
One use case of the nullish coalescing operator (??
) is to assign a default value to a variable.
Let's see how to achieve that:
What is nullish coalescing operator (??
)
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when the left-hand side operand is
null
orundefined
.Otherwise, returns the left-hand side operand.
null
and undefined
are nullish values (they are used to denote the absence of a meaningful value). They are actually values, but they carry no information.
Using the nullish coalescing operator (??
), we can set a fallback value (default value) for the nullish values (undefined
and null
).
Syntax for nullish coalescing operator
Below is the syntax for nullish coalescing operator:
leftExpr ?? rightExpr
From the syntax above:
- If the
leftExpr
has a value that is eithernull
orundefined
(nullish values), then the value in therightExpr
is used as the default or fallback value.
Using the nullish coalescing operator (??
)
Consider two values value1
and value2
, using the syntax for the nullish coalescing operator (??
)
value1 ?? value2
- if
value1
isnull
orundefined
, thevalue2
will set as the default or fallback value - if
value1
is notnull
orundefined
, we keep thevalue1
.
console.log(null ?? "Default value")
console.log(undefined ?? "fallback value")
console.log("firsValue" ?? "secondValue")
The output will be
Default value
fallback value
firstValue
As mentioned earlier, the common use-case of ??
is to provide a default or fallback value to a nullish
value.
Assigning a default value to a variable.
In the code below, we want to assign a fallback or default value to a variable, if the greetings
value is null
.
let greetings = null;
let userGreetings = greetings ?? "Hello World"
console.log("User greetings is now ", userGreetings)
The output will be
User greetings is now Hello World
-greetings
has value of null
hence the ??
operator will set the fallback value to be Hello World
.
- This fallback or default value will then be assigned to
userGreetings
Example 2, Assigning a default value to a property in an object
Consider a situation where you have properties in an object
. One of the values in the key is null
, our task is to assign a fallback or default value to that property.
Let's see how to achieve that
let user = {
firstName: "Emmanuel",
lastName: "Kumah",
nickName: null
}
user.nickName = user.nickName ?? "anonymous";
console.log(user)
The output will be
{firstName: 'Emmanuel', lastName: 'Kumah', nickName: 'anonymous'}
- The property
user.nickName
isnull
hence we can use the??
operator and set the default or fallback value ofuser.nickName
- The value on the righthand side of
??
is then used as the fallback value. - The
user.nickName
property now has a fallback value ofanonymous
instead ofnull
.
Example 3
Let's assign some default values to some variables using the ??
operator
let nullValue = null;
let firstValue = 30;
let secondValue = "someText"
let valueA = nullValue ?? "default value of A"
let valueB = firstValue ?? "default value of B"
let valueC = secondValue ?? "default value of C"
console.log("Value stored in A is the ", valueA)
console.log("Value stored in B is the ", valueB)
console.log("Value stored in C is the ", valueC)
The output will be
Value stored in A is the default value of A
Value stored in B is the 30
Value stored in C is the someText
What is happening in the above?
- The lefthand-side expression
null value
has a value ofnull
hence the??
will return the value on the right-hand side of the operand. That becomes the fallback value stored invalueA
- The value in
firstValue
is 30 ( notnull
orundefined
) hence the value on the left-hand side30
is maintained - The value in
secondValue
is someText (also notnull
orundefined
) hence the value on the left-hand sidesomeText
is maintained
Differences between Logical OR operator (||
) or nullish coalescing operator (??
)
The nullish coalescing operator (??
) is very similar to the logical OR operator (||
) they both return default values.
The major difference is the logical OR operator (||
) will return the right-hand side operand if the left operand is any falsy value whiles the nullish coalescing operator (??
) will return the right-hand side operand only if the left operand is null
or undefined
.
Why the nullish coalescing operator
Previously, when assigning a default value to a variable, we used the ||
operator. If any value on the lefthand-side of the ||
is a falsy value, then the value on the righthand-side of the ||
will be used as the default value.
lefthandExpr || righthandExpr
A falsy
value is any of the 6 values
- false
- undefined
- null
- 0
- ""
- NaN
The challenge with the || operator is, it will not differentiate between false, 0, an empty string "", NaN, null and undefined. They are all considered falsy values. If any of these is the first argument of the ||
, then we'll use the second argument as the result.
In practice, we want to set a fallback or default value only when the variable is null/undefined. Meaning, the value is really unknown or not set.
The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values)
Consider the code below
let age = 0;
console.log(age || 32)
console.log(age ?? 32)
The output will be
32
0
- The age || 32 checks the age for a falsy value, since 0 is a falsy value, it outputs the truthy value
32
- The age ?? 32 checks the age for being
null
orundefined
. Sinceage
is not, it keeps the age as it is (0) - In practice, the
0
is considered a valid value, so should not be replaced with a default value. - The
??
does a perfect job of only setting a fallback value when the value on the lefthand-side of??
is onlynull
orundefined
.
Short circuiting the nullish coalescing operator
Similar to the OR and AND logical operators, the nullish coalescing operator will not evaluate the right-hand side expression, if the left-hand side expression is neither null nor undefined
Challenge
What will the output of the code below be?
let result = "first value" ?? "second value"
console.log(result)
let result2 = undefined ?? "second value"
console.log(result2)
Summary
The nullish coalescing operator ??
helps us set a fallback or default value if the value to the lefthand side of the ??
operator is either null
or undefined
.
Trust you have learned useful tips from this post? Help it reach a wider audience by sharing on your social media platforms. Do send me feedback, would love to read your comment.
Written with love from Ghana. Me daa se (Thank you)