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 (||):

var 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:

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

This means:

var 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"
🌐
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.
Discussions

Is there a "null coalescing" operator in JavaScript? - Stack Overflow
Is there a null coalescing operator in Javascript? For example, in C#, I can do this: String someString = null; var whatIWant = someString ?? "Cookies!"; The best approximation I can figure out for More on stackoverflow.com
🌐 stackoverflow.com
javascript - When should I use ?? (nullish coalescing) vs || (logical OR)? - Stack Overflow
Related to Is there a "null coalescing" operator in JavaScript? - JavaScript now has a ?? operator which I see in use more frequently. Previously most JavaScript code used ||. let userAge = More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
July 8, 2025 - 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.
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 (||):

var 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:

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

This means:

var 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
function 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.

🌐
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: ...
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.
Top answer
1 of 9
980

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
399

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.
🌐
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!

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-nullish-coalescing-operator
JavaScript Nullish Coalescing(??) Operator - GeeksforGeeks
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.
Published   July 12, 2025
🌐
OpenReplay
blog.openreplay.com › mastering-javascript-optional-chaining-and-nullish-coalescing
Mastering JavaScript: optional chaining and nullish coalescing
March 13, 2023 - JavaScript has two types of null values: null and undefined. null represents an intentional absence of a value, while undefined represents an uninitialized or missing value. Sometimes, you might want to use a default value if a variable is either null or undefined. This is where ‘Nullish Coalescing’ comes in.
Top answer
1 of 16
176

You can use the logical 'OR' operator in place of the Elvis operator:

For example displayname = user.name || "Anonymous" .

But Javascript currently doesn't have the other functionality. I'd recommend looking at CoffeeScript if you want an alternative syntax. It has some shorthand that is similar to what you are looking for.

For example The Existential Operator

zip = lottery.drawWinner?().address?.zipcode

Function shortcuts

()->  // equivalent to function(){}

Sexy function calling

func 'arg1','arg2' // equivalent to func('arg1','arg2')

There is also multiline comments and classes. Obviously you have to compile this to javascript or insert into the page as <script type='text/coffeescript>' but it adds a lot of functionality :) . Using <script type='text/coffeescript'> is really only intended for development and not production.

2 of 16
154

2020 Update

JavaScript now has equivalents for both the Elvis Operator and the Safe Navigation Operator.


Safe Property Access

The optional chaining operator (?.) is currently a stage 4 ECMAScript proposal. You can use it today with Babel.

// `undefined` if either `a` or `b` are `null`/`undefined`. `a.b.c` otherwise.
const myVariable = a?.b?.c;

The logical AND operator (&&) is the "old", more-verbose way to handle this scenario.

const myVariable = a && a.b && a.b.c;

Providing a Default

The nullish coalescing operator (??) is currently a stage 4 ECMAScript proposal. You can use it today with Babel. It allows you to set a default value if the left-hand side of the operator is a nullary value (null/undefined).

const myVariable = a?.b?.c ?? 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null ?? 'Some other value';

// Evaluates to ''
const myVariable3 = '' ?? 'Some other value';

The logical OR operator (||) is an alternative solution with slightly different behavior. It allows you to set a default value if the left-hand side of the operator is falsy. Note that the result of myVariable3 below differs from myVariable3 above.

const myVariable = a?.b?.c || 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null || 'Some other value';

// Evaluates to 'Some other value'
const myVariable3 = '' || 'Some other value';
🌐
Can I Use
caniuse.com › mdn-javascript_operators_nullish_coalescing
JavaScript operator: Nullish coalescing operator (`??`) | Can I use... Support tables for HTML5, CSS3, etc
"Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.
🌐
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" ?
🌐
Fjolt
fjolt.com › article › javascript-nullish-coalescing
What is Nullish Coalescing (or ??) in Javascript
In Javascript, the nullish coalescing operator, or ?? operator is used to return the right hand side whenever the left hand side is null or undefined.