🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
Discussions

TIL about the Nullish Coalescing Operator in Javascript (??)
Wait until you learn about the elvis operator More on reddit.com
🌐 r/ProgrammerTIL
18
78
March 30, 2022
What is the ?. operator and Where I can the use ?? Nullish Coalescing Operator in JavaScript - Stack Overflow
I found this pieces of code: Here, What is the ?. JavaScript operator? And Will I be able to use ?? Nullish Coalescing Operator in JavaScript instead of || OR operator according to the mentioned code snippet below? More on stackoverflow.com
🌐 stackoverflow.com
Thoughts on the Null Coalescing (??) operator precedence?
When something relatively new comes out, it's common for the first few games in town to foul up the artistry. Wirth is a towering intellect in this field, but he screwed up the precedence tables in Pascal. Experience will highlight mistakes, and then it's eventually time to design a new language. ?? clearly goes after function-call and field-access, but before arithmetic. The field-access counterpart .? should be on the same level as non-null field-access .. More on reddit.com
🌐 r/ProgrammingLanguages
11
31
April 30, 2024
Null-coalescing in Javascript? - Stack Overflow
In C# you can do the following: string y = null; string x = y ?? "sup stallion"; //x = "sup stallion" since y is null. Where The ?? operator is the null-coalescing operator. And in Javascript I'v... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/programmertil › til about the nullish coalescing operator in javascript (??)
r/ProgrammerTIL on Reddit: TIL about the Nullish Coalescing Operator in Javascript (??)
March 30, 2022 -

Often if you want to say, "x, if it exists, or y", you'd use the or operator ||.

Example:

const foo = bar || 3;

However, let's say you want to check that the value of foo exists. If foo is 0, then it would evaluate to false, and the above code doesn't work.

So instead, you can use the Nullish Coalescing Operator.

const foo = bar ?? 3;

This would evaluate to 3 if bar is undefined or null, and use the value of bar otherwise.

In typescript, this is useful for setting default values from a nullable object.

setFoo(foo: Foo|null) {
  this.foo = foo ?? DEFAULT_FOO;
}
🌐
DEV Community
dev.to › justanordinaryperson › -nullish-coalescing-vs-logical-or-in-javascript-2l88
?? (Nullish coalescing) vs || (Logical OR) in Javascript - DEV Community
June 16, 2024 - Nullish Coalescing Operator (??): This is specifically designed to handle situations where the left operand might be unintentionally left unassigned (null) or missing a a value (undefined).
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Null_coalescing_operator
Null coalescing operator - Wikipedia
October 31, 2025 - As of ColdFusion 11, Railo 4.1, CFML supports the null coalescing operator as a variation of the ternary operator, ?:. It is functionally and syntactically equivalent to its C# counterpart, above. Example: ... Missing values in Apache FreeMarker will normally cause exceptions. However, both missing and null values can be handled, with an optional default value: ... JavaScript's nearest operator is ??, the "nullish coalescing operator", which was added to the standard in ECMAScript's 11th edition.
🌐
W3Schools
w3schools.com › jsref › jsref_oper_nullish.asp
JavaScript Nullish Coalescing Operator
The ?? operator returns the right operand when the left operand is nullish (null or undefined), otherwise it returns the left operand. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: ...
🌐
DEV Community
dev.to › laurieontech › nullish-coalescing-let-falsy-fool-you-no-more-41c0
Nullish Coalescing - Let Falsy Fool You No More - DEV Community
December 13, 2019 - In this example, snippet is set to null. Since we always want a string, we'll reassign it using the or operator. This expression will keep snippet the same unless snippet is falsy. When it's falsy the expression resolves to "code snippet" instead. That's because falsy values in JavaScript are values that are "considered false when encountered in a Boolean context", like our example above.
🌐
V8
v8.dev › features › nullish-coalescing
Nullish coalescing · V8
September 17, 2019 - The nullish coalescing operator (??) acts very similar to the || operator, except that we don’t use “truthy” when evaluating the operator. Instead we use the definition of “nullish”, meaning “is the value strictly equal to null or undefined”. So imagine the expression lhs ??
🌐
Reddit
reddit.com › r/programminglanguages › thoughts on the null coalescing (??) operator precedence?
r/ProgrammingLanguages on Reddit: Thoughts on the Null Coalescing (??) operator precedence?
April 30, 2024 -

Many languages have a "null-coalescing" operator: a binary operator used to unwrap an optional/nullable value, or provide a "default" value if the LHS is null/none. It's usually spelled ?? (as in Javascript, Swift, C#, etc.).

I'm pondering the precedence of such an operator.

Why not just use no precedence? Parenthesis! S-expressions! Polish!

All interesting ideas! But this post will focus on a more "C-style" language perspective.


As for ??, it seems like there's a bit of variety. Let's start with a kind of basic operator precedence for a hypothetical C-style statically typed language with relatively few operators:

precoperatorstypes
1Suffixes: a()-> any type
2High-prec arithmetic: a * binteger, integer -> integer
3Low-prec arithmetic: a + binteger, integer -> integer
4Comparisons: a == binteger, integer -> boolean
5Logic: a && bboolean, boolean -> boolean

There are subtly differences here and there, but this is just for comparisons. Here's how (some) different languages handle the precedence.

  • Below #5:

  • C#

  • PHP

  • Dart

  • Equal to #5

  • Javascript (Kinda; ?? must be disambiguated from && and ||)

  • Between #3 and #4:

  • Swift

  • Zig

  • Kotlin

So, largely 2 camps: very low precedence, or moderately low. From a brief look, I can't find too much information on the "why" of all of this. One thing I did see come up a lot is this: ?? is analogous to ||, especially if they both short-circuit. And in a lot of programming languages with a looser type system, they're the same thing. Python's or comes to mind. Not relevant to a very strict type system, but at least it makes sense why you would put the precedence down that. Score 1 for the "below/equal 5" folk.


However, given the divide, it's certainly not a straightforward problem. I've been looking around, and have found a few posts where people discuss problems with various systems.

  • https://forums.swift.org/t/nil-coalescing-operator-precedence/2954

  • https://www.codeproject.com/Tips/721145/Beware-The-null-coalescing-operator-is-low-in-the

These seem to center around this construct: let x = a() ?? 0 + b() ?? 0. Operator precedence is largely cultural/subjective. But if I were a code reviewer, attempting to analyze a programmer's intent, it seems pretty clear to me that the programmer of this wanted x to equal the sum of a() and b(), with default values in case either were null. However, no one parses ?? as having a higher precedence than +.

This example might be a bit contrived. To us, the alternate parse of let x = a() ?? (0 + b()) ?? 0 because... why would you add to 0? And how often are you chaining null coalescing operators? (Well, it can happen if you're using optionals, but it's still rare). But, it's a fairly reasonable piece of code. Those links even have some real-world examples like this people have fallen for.


Looking at this from a types perspective, I came to this conclusion; In a strongly-typed language, operator precedence isn't useful if operators can't "flow" from high to low precedence due to types.

To illustrate, consider the expression x + y ?? z. We don't know what the types of x, y, and z are. However, if ?? has a lower precedence than +, this expression can't be valid in a strictly typed language, where the LHS of ?? must be of an optional/nullable type.

If you look back at our hypothetical start table, you can see how operator types "flow" through precedence. Arithmetic produces integers, which can be used as arguments to comparisons. Comparisons produce booleans, which can be used as arguments to logical operators.

This is why I'd propose that it makes sense for ?? to have a precedence, in our example, between 1 and 2. That way, more "complex" types can "decay" though the precedence chain. Optionals are unwrapped to integers, which are manipulated by arithmetic, decayed to booleans by comparison, and further manipulated by logic.


Discussion questions:

  1. What are some reasons for choosing the precedence of ?? other than the ones discussed?

  2. Have any other languages done something different with the precedence, and why?

  3. Has anyone put the precedence of ?? above arithmetic?

Thanks!

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

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.

🌐
TypeScript
typescriptlang.org › play › 3-7 › syntax-and-messaging › nullish-coalescing.ts.html
TypeScript: Playground Example - Nullish Coalescing
) { // With null-coalescing operator config.name = config.name ?? "(no name)"; config.items = config.items ?? -1; config.active = config.active ?? true; // Current solution config.name = typeof config.name === "string" ? config.name : "(no name)"; config.items = typeof config.items === "number" ?
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'
🌐
daily.dev
daily.dev › home › blog › webdev › nullish coalescing operator (??) in javascript - what is it and how to use it?
Nullish Coalescing Operator (??) In JavaScript - What Is It And How To Use It?
November 1, 2021 - According to MDN, the nullish coalescing 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 type of operator is handy ...
🌐
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 ||, ...
🌐
Medium
medium.com › @gabrielairiart.gi › advanced-javascript-use-of-nullish-coalescing-and-optional-chaining-and-for-efficient-coding-7d1d3fe3eedf
Advanced JavaScript: Use of Nullish Coalescing ?? and Optional Chaining and ?. for Efficient Coding | by Gabriela Iriart | Medium
March 22, 2024 - When juxtaposing Nullish Coalescing with Optional Chaining, it’s crucial to grasp that they fulfill distinct yet complementary roles. Nullish Coalescing ensures a variable is assigned a definitive value if it’s found to be null or undefined, thereby preventing the variable from remaining in an indeterminate state.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-advanced-operators
Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment
January 4, 2024 - When you’re inspecting JavaScript code, you may find an expression using a double question mark (??), as in the code below: ... The double question mark is a logical operator that returns the expression on the right-hand side of the mark when the expression on the left-hand side is null or undefined · This operator is also known as the nullish coalescing operator.