Nullish coalescing operator

Photo by Ana Municio on Unsplash

Nullish coalescing operator

The nullish coalescing operator chooses the first defined value from the expression. It returns the second value if first value is null or undefined.

What is Nullish coalescing operator ??

The Nullish coalescing operator ?? is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This operator is recently added to ECMAScript's 11th edition (ES2020).

Syntax

let result = value1 ?? value2

Why should we use this operator ??

It provides a default value when the first value turns out to be null or undefined.
For example:

let name = null
const result = name ?? "Anonymous" // "Anonymous"

let gender = undefined
const answer = gender ?? "Exploring" // "Exploring"

Why to use ?? instead of ||

The falsy values for || operator is

  1. null
  2. undefined
  3. ""(empty string)
  4. 0
  5. NaN
  6. false

Whereas falsy values for ?? operator are null and undefined.

So for specific conditions, we can use the ?? operator like
When we are taking user data, we ask for input from the user, whether it be name or email. We are not able to process null or undefined inputs. So we would like the code to have default values taken instead of the null or undefined.

But If the user is required to give answers like false or 0. The || operator will consider it falsy value and take the default value which is wrong.

For example:

let number = 0
const result = number || "-"  // "-"

let num = 0
const answer = num ?? "-"  // 0

In practice, the number can be 0.
|| operator doesn't take 0 as truthy value and chooses the 2nd expression -
But if we use ?? operator, it takes 0 as user input, which is needed here.

Short-circuiting

Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined.

For example:

const answer = "left-hand side" ?? "right-hand side" // "left-hand side"

The operator ?? does not evaluate the second value because the first value is a string, which is not null or undefined.

const answer = null ?? "right-hand side" // "right-hand side"

This example evaluates the second expression because the first one is null

Chaining with the || or && operator

A SyntaxError will occur if you combine the logical OR or AND operator directly with the nullish coalescing operator.

const answer = undefined ?? null || 'the answer'; // SyntaxError

However, the error can be avoided by wrapping the expression on the right of the ?? operator in parentheses to explicitly specify the operator precedences:

let answer = undefined ?? (null || 'the answer'); // 'the answer'

Precedence

Precedence by MDN Operator name Operator Symbol
13 Multiplication and Division * /
12 Addition and Subtraction + -
5 Logical AND &&
4 Logical OR and Nullish coalescing || ??
2 Assignment =

Relationship with the optional chaining operator ?.

The optional chaining operator ?. reads property value present deep within a chain of connected objects without checking each reference in the chain is valid or not.

It returns undefined in following scenarios of error:

  1. If a reference is nullish meaning null or undefined
  2. When used with function calls, if the given function does not exist

So the nullish coalescing operator ?? can return default value if used with it to avoid returning undefined to user.

For example:

let code = { message: "HI USER" };

let answer = (code.message?.toLowerCase() ?? "not found"); // "hi user"
let answer1 = (code.notMessage?.toLowerCase() ?? "not found"); // "not found"

In this code snippet, the reference is nullish i.e the object code has no property named notMessage. So the ?. operator returns undefined and then ?? operator returns default value.

let code = { 
  message: "HI USER",
  x:function(){return 'HI USER'.toLowerCase()},
  y:function(){} 
};

let answer = (code?.x() ?? "not found"); // "hi user"
let answer1 = (code?.y() ?? "not found"); // "not found"

In this code snippet, the function y is empty meaning function y doesn't returns anything. So the ?. operator returns undefined and then ?? operator returns default value.

Examples

  1. let x = null ?? undefined // undefined
    
  2. let y = undefined ?? null; // null
    
  3. let z = null ?? undefined ?? null ?? "hi"; // "hi"
    
  4. let s = null ?? undefined ?? NaN ?? 0; // NaN
    
  5. let q = null ?? undefined ?? "null" ?? 2; // "null"
    
  6. let r = undefined ?? null ?? false ?? 0 ?? "" ?? NaN; // false
    

Conclusion

  • The nullish coalescing operator ?? chooses the first defined value from the expression.
  • ?? operator has a lower precedence from && and equal precedence with ||, so we have to add parentheses when using it in an expression with these operators.
  • ?? operator can be directly chained with ?. operator without parentheses

Resources