Called "optional chaining", it's currently a TC39 proposal in Stage 4. A Babel plugin however is already available in v7.

Example usage:

const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined
Answer from Brent L on Stack Overflow
๐ŸŒ
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.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ null-coalescing-operator-in-javascript-with-ecmascript-2020
Null Coalescing Operator in JavaScript with ECMAScript 2020
March 22, 2023 - Though, we could also ditch the if statement fully and use a short-circuit AND operator instead to shorten the statements: let x = 10; let y = 20; (x+y) > 20 && console.log("x+y is greater than 20"); (x+y) > 20 evaluates to true so the next block is entered, and the message is printed. ... If the (x+y) > 20 was falsy (we'll talk about this in a second), the JavaScript interpreter wouldn't even look at the second part of the expression, and the block would never run.
๐ŸŒ
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 - The Nullish Coalescing Operator allows us to check if a value is `null` or `undefined`, and provide a fallback value if that is the case.
๐ŸŒ
Go Make Things
gomakethings.com โ€บ the-nullish-coalescing-operator-in-vanilla-js-sorry-the-what-now
The nullish coalescing operator in vanilla JS (sorry, the what now?) | Go Make Things
It works a lot like the or operator, but instead of checking for all falsy values, it only runs if the value on the left side is null or undefined.
๐ŸŒ
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.
Published ย  June 10, 2024
Find elsewhere
๐ŸŒ
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 - The use of Nullish Coalescing (??) and Optional Chaining (?.) operators in JavaScript can streamline your code and enhance readability, but it's essential to consider their impact on performance and when they are most appropriately used.
๐ŸŒ
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 - As JavaScript developers, we've all been there - having to check if a variable is null or undefined before using it. 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 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.

๐ŸŒ
Medium
medium.com โ€บ version-1 โ€บ the-nullish-coalescing-operator-in-javascript-721428ef97ca
The Nullish Coalescing Operator in JavaScript | by Miguel Angel Muรฑoz | Version 1 | Medium
September 29, 2022 - The nullish coalescing operator treats undefined and null as specific values and so does the optional chaining operator (?.) which is useful to access a property of an object which may be null or undefined.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-advanced-operators
Advanced JavaScript Operators โ€“ Nullish Coalescing, Optional Chaining, and Destructuring Assignment
January 4, 2024 - Hi Everyone! In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators. These three operators will help you write clearer and less error-p...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ javascript โ€บ javascript nullish coalescing operator
JavaScript Nullish Coalescing Operator
September 1, 2008 - The Nullish Coalescing operator in JavaScript is represented by two question marks (??). It takes two operands and returns the first operand if it is not null or undefined. Otherwise, it returns the second operand.
๐ŸŒ
W3Schools
w3schools.com โ€บ typescript โ€บ typescript_null.php
TypeScript Null & Undefined
Optional chaining is a JavaScript feature that works well with TypeScript's null handling. It allows accessing properties on an object that may or may not exist, using compact syntax. It can be used with the ?. operator when accessing properties.
๐ŸŒ
JavaScript Tutorial
javascripttutorial.net โ€บ home โ€บ javascript tutorial โ€บ javascript nullish coalescing operator
JavaScript Nullish Coalescing Operator
October 6, 2023 - Summary: in this tutorial, youโ€™ll learn about the JavaScript nullish coalescing operator (??) that accepts two values and returns the second value if the first one is null or undefined.
๐ŸŒ
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.
๐ŸŒ
Marius Schulz
mariusschulz.com โ€บ blog โ€บ nullish-coalescing-the-operator-in-typescript
Nullish Coalescing: The ?? Operator in TypeScript โ€” Marius Schulz
August 14, 2021 - All other JavaScript values will produce the value true when coerced to a Boolean and are thus considered truthy. The ?? operator can be used to provide a fallback value in case another value is null or undefined.
๐ŸŒ
OpenReplay
blog.openreplay.com โ€บ mastering-javascript-optional-chaining-and-nullish-coalescing
Mastering JavaScript: optional chaining and nullish coalescing
The symbol used to denote Nullish Coalescing in JavaScript is the ?? (double question mark). This operator checks if the value on the left side is null or undefined. If it is, it returns the value on the right side; otherwise, it returns the ...
๐ŸŒ
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!