🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals
Nullish coalescing operator '??'
On the other hand, the nullish coalescing operator ?? was added to JavaScript only recently, and the reason for that was that people weren’t quite happy with ||.
binary operator that is part of the syntax for a basic conditional expression in several programming languages
The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as (in alphabetical order): C# since version 2.0, … Wikipedia
🌐
Wikipedia
en.wikipedia.org › wiki › Null_coalescing_operator
Null coalescing operator - Wikipedia
October 31, 2025 - JavaScript's nearest operator is ??, the "nullish coalescing operator", which was added to the standard in ECMAScript's 11th edition. In earlier versions, it could be used via a Babel plugin, and in TypeScript.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
However, due to || being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any falsy value (including 0, '', NaN, false, etc.) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values. ... const count = 0; const text = ""; const qty = count || 42; const message = text || "hi!"; console.log(qty); // 42 and not 0 console.log(message); // "hi!" and not "" 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):
Top answer
1 of 16
2331

Update

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

Old Answer

Please check compatibility before using it.


The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

Copyvar whatIWant = someString || "Cookies!";

There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.


Clarification

Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:

Copyalert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

This means:

Copyvar whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
2 of 16
82
Copyfunction coalesce() {
    var len = arguments.length;
    for (var i=0; i<len; i++) {
        if (arguments[i] !== null && arguments[i] !== undefined) {
            return arguments[i];
        }
    }
    return null;
}

var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);

// xyz.val now contains 5

this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.

🌐
freeCodeCamp
freecodecamp.org › news › what-is-the-nullish-coalescing-operator-in-javascript-and-how-is-it-useful
What is the Nullish Coalescing Operator in JavaScript, and how is it useful
May 5, 2023 - By Dillion Megida The Nullish Coalescing Operator is a new logical operator in JavaScript introduced in ES 2020. In this article, we'll understand how this operator works. There are over four logical operators in JavaScript: the AND &&, OR ||, ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing_assignment
Nullish coalescing assignment (??=) - JavaScript | MDN
The nullish coalescing assignment (??=) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish (null or undefined).
🌐
Trevor Lasn
trevorlasn.com › home › blog › javascript's ??= operator: default values made simple
JavaScript's ??= Operator: Default Values Made Simple
November 5, 2024 - The nullish coalescing assignment operator ??= is relatively new to JavaScript. It was officially added in ECMAScript 2021 (ES12) as part of the “Logical Assignment Operators” proposal.
Find elsewhere
Top answer
1 of 9
993

The OR operator || uses the right value if left is falsy, while the nullish coalescing operator ?? uses the right value if left is null or undefined.

These operators are often used to provide a default value if the first one is missing.

But the OR operator || can be problematic if your left value might contain "" or 0 or false (because these are falsy values):

console.log(12 || "not found") // 12
console.log(0  || "not found") // "not found"

console.log("jane" || "not found") // "jane"
console.log(""     || "not found") // "not found"

console.log(true  || "not found") // true
console.log(false || "not found") // "not found"

console.log(undefined || "not found") // "not found"
console.log(null      || "not found") // "not found"

In many cases, you might only want the right value if left is null or undefined. That's what the nullish coalescing operator ?? is for:

console.log(12 ?? "not found") // 12
console.log(0  ?? "not found") // 0

console.log("jane" ?? "not found") // "jane"
console.log(""     ?? "not found") // ""

console.log(true  ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null      ?? "not found") // "not found"

While the ?? operator isn't available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:

The ?? operator was added to TypeScript 3.7 back in November 2019.

And more recently, the ?? operator was included in ES2020, which is supported by Node 14 (released in April 2020).

When the nullish coalescing operator ?? is supported, I typically use it instead of the OR operator || (unless there's a good reason not to).

2 of 9
403

In short

The Nullish Coalescing Operator ?? distinguishes between:

  • nullish values (null, undefined)
  • falsey but defined values (false, 0, '' etc.)

|| (logical OR) treats both of these the same.

I created a simple graphic to illustrate the relationship of nullish and falsey values in JavaScript:

Further explanation:

let x, y

x = 0
y = x || 'default'            // y = 'default'
y = x ?? 'default'            // y = 0

As seen above, the difference between the operators ?? and || is that one is checking for nullish values and one is checking for falsey values. However, there are many instances where they behave the same. That is because in JavaScript every nullish value is also falsey (but not every falsey value is nullish).

Using what we learned above we can create a few examples for different behavior:

let y

y = false || 'default'       // y = 'default'
y = false ?? 'default'       // y = false

y = 0n || 'default'          // y = 'default'
y = 0n ?? 'default'          // y = 0n

y = NaN || 'default'         // y = 'default'
y = NaN ?? 'default'         // y = NaN

y = '' || 'default'          // y = 'default'
y = '' ?? 'default'          // y = ''

Since the new Nullish Coalescing Operator can differentiate between no value and a falsey value, it can be beneficial if you, for example, need to check if there is no string or an empty string. Generally, you probably want to use ?? instead of || most of the time.

Last and also least here are the two instances where they behave the same:

let y

y = null || 'default'        // y = 'default'
y = null ?? 'default'        // y = 'default'

y = undefined || 'default'   // y = 'default'
y = undefined ?? 'default'   // y = 'default'
🌐
DEV Community
dev.to › efkumah › why-the-nullish-coalescing-operator-was-introduced-in-es2020-1l71
Why the nullish coalescing operator was introduced in ES2020 - DEV Community
February 13, 2022 - 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 · The nullish coalescing operator (??) is very similar to the logical OR operator (||) they both return default values.
🌐
freeCodeCamp
freecodecamp.org › news › nullish-coalescing-operator-in-javascript
How the Nullish Coalescing Operator Works in JavaScript
December 22, 2020 - The || operator works great but sometimes we only want the next expression to be evaluated when the first operand is only either null or undefined. Therefore, ES11 has added the nullish coalescing operator.
🌐
Clubmate
clubmate.fi › logical-operators
JavaScript logical operators and the new nullish coalescing operator – clubmate.fi
The nullish coalescing operator is the newest addition to the JavaScript logical operator family. It was published in 2020. There are three…
🌐
Stack Abuse
stackabuse.com › null-coalescing-operator-in-javascript-with-ecmascript-2020
Null Coalescing Operator in JavaScript with ECMAScript 2020
March 22, 2023 - JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator, which was added to the language with ECMAScript 2020.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-advanced-operators
Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment
January 4, 2024 - It’s a new feature introduced in JavaScript ES2020 that allows you to check for null or undefined values in a more concise way. The syntax for the nullish coalescing operator is very simple. It consists of two question marks ??
🌐
DEV Community
dev.to › jaimaldullat › why-is-the-nullish-coalescing-operator-essential-in-javascript-4g2j
Why Is the Nullish Coalescing Operator(??) Essential in JavaScript? - DEV Community
November 9, 2023 - This results in a lot of repetitive conditional checks that can clutter up our code. With the introduction of the nullish coalescing operator in ECMAScript 2020, we have a cleaner way to handle null or undefined values.
Top answer
1 of 5
37

|| is a logical or. It returns the first truthy operand* (the last value evaluated). So

var myHeader = headers || {'Content-type':'text/plain'};

Returns "headers" if it's truthy (and if it's null or undefined, that value is coreced into "false"). If it's falsey, it returns the second operand. I don't believe this has a very specific name in javascript, just something general like "default argument value".

| is a bitwise or. It is a mathematical operation and does something completely different. That operator doesn't even make sense here (and it will generally just produce 0 as a result). Wherever you saw that, it was surely a typo, and they meant to use logical or.

So go with that first method (a = b || c).

* "Logical or" is also known as "logical disjunction" or "inclusive disjunction". Javascript, like all programming languages, evaluates logical statements using short-circuit evaluation. With logical-or expressions, it evaluates each operand for truthiness and stops on the first true one (and returns that value). If there are no truthy operands, it still had to go through all of them, so it returns the last operand, still the last one it evaluated. Logical and (&&) is similarly short-circuited by stopping on the first falsey operand.

2 of 5
5

Nullish coalescing operator is supported now by javascript(es2020)

As the mozilla doc says:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/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.

Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples.

// Assigning a default value to a variable (old way but in some cases we need this)
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty);     // 42 and not 0
console.log(message); // "hi!" and not ""

// Assign default value when we want to skip undefined/null only
// in most cases we need this, because (0,"",false) are valid values to our programs
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

For more info read this example provided by kent c dods about fallback to default value in the past and now: https://kentcdodds.com/blog/javascript-to-know-for-react#nullish-coalescing-operator

🌐
Fsjs
fsjs.dev › nullish-coalescing-operator-beyond-default-values
The Power of the Nullish Coalescing Operator: Beyond Default Values — Full Stack Javascript Developer
If userInput is '', 0, or false, you’ll get 'Guest' instead of the meaningful falsy value. The nullish coalescing operator (??) was introduced in ES2020 to address this: it only falls back when the left-hand side is null or undefined, not ...
🌐
Medium
medium.com › @mfarazali › nullish-coalescing-operator-in-javascript-c63cab8cce41
Nullish coalescing operator (??) in Javascript | by Muhammad Faraz Ali | Medium
March 20, 2024 - Nullish coalescing operator (??) in Javascript Nullish coalescing operator (??), introduced in ECMAScript 2020 (ES11), simplifies the process of handling default values for variables that might be …
🌐
Medium
commandcodes.medium.com › ecmascript-2020-es11-exploring-the-nullish-coalescing-operator-in-javascript-ae79d6d7a2a6
ECMAScript 2020 (ES11): Exploring the Nullish Coalescing Operator in JavaScript | by Musa Abdulkabir | Medium
January 4, 2024 - JavaScript, the ubiquitous programming ... code readability. One such addition is the Nullish Coalescing Operator, introduced in ECMAScript 2020 (ES11)....