JavaScript nullish coalescing ?? | Operator

  • by

JavaScript nullish coalescing operator is written as two question marks ??. This operator is a logical operator that accepts two values.

leftExpr ?? rightExpr

This operator returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

JavaScript nullish coalescing

Simple example code where nullish coalescing operator returns the second value (value2) if the first value (value2) is null or undefined.

<!DOCTYPE html>
    const name = null ?? 'John';

    const age = undefined ?? 28;

    const baz = 0 ?? 42;



JavaScript nullish coalescing

Why use a nullish coalescing operator?

Answer: If you want to assign a default value to a variable, a common pattern was to use the logical OR operator (||):

let msg;

//  msg is never assigned any value so it is still undefined
let greeting= msg|| 'Hello!';

It works fine and will assign the Hello string but logical OR operator (||) sometimes confuses if you consider 0 or empty strings '' as a valid value like this:

let count = 0;
let result = count || 1; // 1

The result is 1, not 0, which you may not expect.

The nullish coalescing operator helps you to avoid this pitfall. It only returns the second value when the first one is either null or undefined.


Similar to the logical OR and AND operators, the nullish coalescing operator does not evaluate the second value if the first operand is neither undefined nor null.

let result = 1 ?? console.log(1/0);
console.log(res); // 1

In this example, the operator ?? does not evaluate the expression 1/0 because the first value is 1, which is not null and undefined.

No chaining with AND or OR operators

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

null || undefined ?? "foo"; // raises a SyntaxError
true || undefined ?? "foo"; // raises a SyntaxError

However, providing parenthesis to explicitly indicate precedence is correct:

(null || undefined) ?? "foo"; // returns "foo"

Do comment if you have any doubts or suggestions on this Js operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.