Why the nullish coalescing operator was introduced in ES2020

Emmanuel Fordjour Kumah - Feb 9 '22 - - Dev Community

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 additon 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 or undefined.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
Enter fullscreen mode Exit fullscreen mode

From the syntax above:

  • If the leftExpr has a value which is either null or undefined (nullish values), then the value in the rightExpr 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 
Enter fullscreen mode Exit fullscreen mode
  • if value1 is null or undefined, the value2 will set as the default or fallback value
  • if value1 is not null or undefined, we keep the value1.
console.log(null ?? "Default value")
console.log(undefined ?? "fallback value")
console.log("firsValue" ?? "secondValue")
Enter fullscreen mode Exit fullscreen mode

The output will be

Default value
fallback value
firstValue
Enter fullscreen mode Exit fullscreen mode

As mentioned earlier, the common usecase 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)
Enter fullscreen mode Exit fullscreen mode

The output will be

User greetings is now  Hello World
Enter fullscreen mode Exit fullscreen mode

-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)
Enter fullscreen mode Exit fullscreen mode

The output will be

{firstName: 'Emmanuel', lastName: 'Kumah', nickName: 'anonymous'}
Enter fullscreen mode Exit fullscreen mode
  • The property user.nickName is null hence we can use the ?? operator and set the default or fallback value of user.nickName
  • The value on the righthand side of ?? is then used as the fallback value.
  • The user.nickName property now has a fallback value of anonymous instead of null.

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

What is happening in the above ?

  • The lefthand-side expression nullValue has a value of null hence the ?? will return the value on the right-hand side of the operand.That becomes the fallback value stored in valueA
  • The value in firstValue is 30 ( not null or undefined) hence the value on the left-hand side 30 is maintained
  • The value in secondValue is someText (also not null or undefined) hence the value on the left-hand side someText 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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

The output will be

32
0
Enter fullscreen mode Exit fullscreen mode
  • The age || 32 checks the age for a falsy value, since 0 is a falsy value, it output the truthy value 32
  • The age ?? 32 checks the age for being null or undefined. Since age is not, it keeps the age as it is (0)
  • In practice, the 0 is consider a valid value, so should not be repalced with a default value.
  • The ?? does perfect job of only setting a fallback value when the value on the lefthand-side of ?? is only null or undefined.

Short circuting the nullish coalescing operator

Similar to the OR and AND logical operators, the nullish coalescing opearator 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)
Enter fullscreen mode Exit fullscreen mode

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 learnt useful tips from this post ? Help it reach a wider audience by sharing on your social media platforms. Do send me a feedback, would love to read your comment.

Written with love from Ghana. Me daa se (Thank you)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .