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"
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
null || undefined ?? "foo"; // raises a SyntaxError true && undefined ?? "foo"; // raises a SyntaxError · Instead, provide parenthesis to explicitly indicate precedence: ... In this example, we will provide default values but keep values other than null or undefined.
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.

🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals
Nullish coalescing operator '??'
The nullish coalescing operator isn’t anything completely new. It’s just a nice syntax to get the first “defined” value of the two. We can rewrite result = a ?? b using the operators that we already know, like this: ... Now it should be absolutely clear what ?? does. Let’s see where it helps. The common use case for ?? is to provide a default value. For example, here we show user if its value isn’t null/undefined, otherwise Anonymous:
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing_assignment
Nullish coalescing assignment (??=) - JavaScript | MDN
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const:
🌐
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 - Let us illustrate it with an example: ... In the above case, the `||` operator returns "60" because "0" is evaluated as a falsy value. In addition, `||` is a boolean logical operator, which is why it coerced "0" to a falsy value, and returned ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-nullish-coalescing-operator
JavaScript Nullish Coalescing(??) Operator - GeeksforGeeks
This is a new operator introduced by javascript. This operator is represented by x ??= y and it is called Logical nullish assignment operator. Only if the value of x is nullish then the value of y will be assigned to x that means if the value of x is null or undefined then the value of y will be ass · 2 min read Nullish Coalescing ...
Published   June 10, 2024
🌐
TutorialsPoint
tutorialspoint.com › home › javascript › javascript nullish coalescing operator
What is a "null coalescing" operator in JavaScript?
September 1, 2008 - In the example below, we created the object containing the mobile-related properties. After that, we access the properties of the object and initialize the variables with value. The object doesn't contain the 'brand' property, so the code ...
🌐
Codecademy
codecademy.com › docs › javascript › nullish coalescing
JavaScript | Nullish Coalescing | Codecademy
January 8, 2025 - Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity. Beginner Friendly.Beginner Friendly15 hours15 hours ... The following example demonstrates the use of the nullish coalescing operator to return 18 as a default or fallback value when the variable age is null or undefined:
🌐
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: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Find elsewhere
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript nullish coalescing operator
JavaScript Nullish Coalescing Operator
October 6, 2023 - Technically, the nullish coalescing operator is equivalent to the following block: const result = value1; if(result === null || result === undefined) { result = value2; }Code language: JavaScript (javascript) A nullish value is a value that ...
🌐
freeCodeCamp
freecodecamp.org › news › nullish-coalescing-operator-in-javascript
How the Nullish Coalescing Operator Works in JavaScript
December 22, 2020 - So from all of the above examples, it’s clear that the result of the operation x ?? y is y only when x is either undefined or null. In all the other cases, the result of the operation will always be x. As you have seen, the nullish coalescing operator is really useful when you only care about the null or undefined value for any variable. Starting with ES6, there are many useful additions to JavaScript ...
🌐
TutorialsPoint
tutorialspoint.com › home › javascript › javascript nullish coalescing operator
JavaScript Nullish Coalescing Operator
September 1, 2008 - In the example below, we created the object containing the mobile-related properties. After that, we access the properties of the object and initialize the variables with value. The object doesn't contain the 'brand' property, so the code ...
🌐
CoreUI
coreui.io › answers › how-to-use-nullish-coalescing-in-javascript
How to use nullish coalescing in JavaScript · CoreUI
November 18, 2025 - Use the nullish coalescing operator (??) to provide default values only when the left side is null or undefined. const userSettings = { theme: null, notifications: false, timeout: 0, username: undefined } // Nullish coalescing - only null/undefined ...
🌐
Web Dev Simplified
blog.webdevsimplified.com › 2020-03 › javascript-null-coalesce
JavaScript Null Coalesce
It is possible to use the null coalesce operator with other logical operators like AND (&&) and OR (||), but parenthesis must be used in order to specify the order in which the logical operators evaluate. 0 || null ?? 10 // Uncaught SyntaxError: Unexpected token '??' (0 || null) ?? 10 // 10 · In the above example when no parenthesis are used an error is thrown since JavaScript is not sure what order to evaluate the operators.
🌐
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;
}
🌐
Chris Pietschmann
pietschsoft.com › post › 2008 › 10 › 14 › javascript-gem-null-coalescing-using-the-or-operator
JavaScript: Null Coalesce using the || Operator | Chris Pietschmann
October 14, 2008 - Below is an example of what I used to do Previous to learning this trick: var middle = (stooge["middle-name"] != null ? stoog["middle-name"] : "(none)"); var status = (flight.status != null ? flight.status : "unknown"); This new trick makes the code much easier to read, and checks for undefined *also so I no longer need to worry about the value being equal to *undefined in some rare circumstance. JavaScript: The Good Parts by Douglas Crockford.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-advanced-operators
Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment
January 4, 2024 - As you can see, the Nullish Coalescing Operator is a great feature that can make your code more concise and reliable. For safety reasons, the double question mark can’t be used together with JavaScript OR (||) and AND (&&) operators without parentheses () separating the operators. For example, the following code tries to see if either firstName or lastName variable can be used as the value of username before using "Guest" as its value:
🌐
HackerNoon
hackernoon.com › a-nullish-coalescing-in-js-tutorial-for-normal-people
A Nullish Coalescing (in JS) Tutorial for Normal People | HackerNoon
June 24, 2023 - Nullish coalescing is a new feature that helps make that a whole lot easier. In this post, we’ll explain nullish coalescing.
🌐
OpenReplay
blog.openreplay.com › mastering-javascript-optional-chaining-and-nullish-coalescing
Mastering JavaScript: optional chaining and nullish coalescing
In this example, the age is falsy but not null or undefined, so the ?? operator will not work and will return the value of user.age. But in the case of user.address, either null or undefined, the ?? operator will return the default value Not specified. When using the Nullish Coalescing operator with objects, be careful when the default value is also an object because JavaScript objects are compared by reference, not by value.
🌐
Fjolt
fjolt.com › article › javascript-nullish-coalescing
What is Nullish Coalescing (or ??) in Javascript
It is also possible to chain the nullish coalescing operator, as shown below: // Is set to "default text" let x = null ?? undefined ?? "default text"; But you cannot chain it with the logical || operator, unless with parenthesis: // Errors out: let x = 0 || undefined ?? "default text"; // Returns "default text"; let y = (0 || undefined) ?? "default text"; ... Javascript loops: for vs forEach vs for..