Optional chaining was introduced in ES2020 and it can be used with the nullish coalescing operator.

const myNestedProp = user?.profile?.name?.last_name ?? null;

// It will print the value of the nested prop `last_name`
// or null if it's undefined
console.log(myNestedProp);

https://github.com/tc39/proposal-optional-chaining

Answer from parse 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 treats undefined and null as specific values. So does the optional chaining operator (?.), which is useful to access a property of an object which may be null or undefined.
🌐
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.
Top answer
1 of 1
1

I see two possible options:

  1. Do the nullish coalescing property-by-property, or

  2. Use a utility function

Property by property

Fairly plodding (I'm a plodding developer):

// Default `ExampleProps` here −−−−−−−−−−−−−−−vvvvv
export default function Example({ ExampleProps = {} }) {
    // Then do the nullish coalescing per-item
    const content = ExampleProps.content ?? "";
    const title = ExampleProps.title ?? "Missing Title";
    const date = ExampleProps.date ?? "";
    const featuredImage = ExampleProps.featuredImage ?? {},
    const author = ExampleProps.author ?? {},
    const tags = ExampleProps.tags ?? [];
    // ...

Utility function

Alternatively, use a utility function along these lines to convert null values (both compile-time and runtime) to undefined, so you can use destructuring defaults when destructuring the result. The type part is fairly straightforward:

type NullToUndefined<Type> = {
    [key in keyof Type]: Exclude<Type[key], null>;
}

Then the utility function could be something like this:

function nullToUndefined<
    SourceType extends object,
    ResultType = NullToUndefined<SourceType>
>(object: SourceType) {
    return Object.fromEntries(
        Object.entries(object).map(([key, value]) => [key, value ?? undefined])
    ) as ResultType;
}

or like this (probably more efficient in runtime terms):

function nullToUndefined<
    SourceType extends object,
    ResultType = NullToUndefined<SourceType>
>(object: SourceType) {
    const source = object as {[key: string]: any};
    const result: {[key: string]: any} = {};
    for (const key in object) {
        if (Object.hasOwn(object, key)) {
            result[key] = source[key] ?? undefined;
        }
    }
    return result as ResultType;
}

Note that Object.hasOwn is very new, but easily polyfilled. Or you could use Object.prototype.hasOwn.call(object, key) instead.

(In both cases within nullToUndefined I'm playing a bit fast and loose with type assertions. For a small utility function like that, I think that's a reasonable compromise provided the inputs and outputs are well-defined.)

Then:

export default function Example({ ExampleProps }) {
    const {
        content = "",
        title = "Missing Title",
        date = "",
        featuredImage = {},
        author = {},
        tags = [],
    } = nullToUndefined(ExampleProps || {});
    //  ^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−^
    // ...

Playground link

🌐
OpenReplay
blog.openreplay.com › mastering-javascript-optional-chaining-and-nullish-coalescing
Mastering JavaScript: optional chaining and nullish coalescing
In this example, the getUserName function takes an object as an argument and returns the name property of the object if it exists. If the name property is null or undefined, the Optional Chaining operator( ?.) will return null or undefined, and the Nullish Coalescing operator (??) will use the default value of ‘John Doe’.
🌐
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 - Since JavaScript returns a boolean value of true when your looking at a variable that is not set to null or undefined, you can use the || (or) operator to do null coalescing. Basically, as long as the first value is not null or undefined it’s ...
Find elsewhere
🌐
egghead.io
egghead.io › lessons › javascript-use-the-nullish-coalescing-operator-to-set-object-defaults
Use the Nullish Coalescing Operator to Set Object Defaults | egghead.io
The nulliish coalescing operator (??) allows us to be more explicit when setting object defaults. It allows us to ensure that only values that are 'null...
Published   December 10, 2019
🌐
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 - We can solve the problem with the help of the nullish coalescing operator. By replacing `||` with `??` we get the correct value, which is "0" in this case. These two operators work very well together. If you remember from our previous post about the Optional Chaining operator, we use it to access chained object properties ...
🌐
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 - 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. On the other hand, Optional Chaining facilitates the secure traversal of potentially undefined object properties, safeguarding against runtime errors that could occur when attempting to access properties on null or undefined objects.
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.

🌐
V8
v8.dev › features › nullish-coalescing
Nullish coalescing · V8
Default assignment inside object ... if the property is strictly equal to undefined, and if so defaults the assignment. But these strict equality tests for only undefined aren’t always desirable, and an object to perform destructing on isn’t always available. For instance, maybe you want to default on a function’s return values (no object to destructure). Or maybe the function returns null (which is common for DOM APIs). These are the times you want to reach for nullish coalescing...
🌐
LogRocket
blog.logrocket.com › home › optional chaining and nullish coalescing in javascript
Optional chaining and nullish coalescing in JavaScript - LogRocket Blog
June 4, 2024 - However, note that if temperature happens to have a toCelsius property that just isn’t a function, this will still cause an error: TypeError: temperature.toCelsius is not a function. In addition to accessing nested values, another common pattern in JavaScript is to use the logical OR operator (||) to coalesce values because it returns the first truthy operand, not a Boolean.
🌐
Reality Ripple
udn.realityripple.com › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing_operator
Nullish coalescing operator (??) - JavaScript
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.
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_nullish_coalescing_operator.htm
JavaScript - Nullish Coalescing Operator
The object doesn't contain the 'brand' property, so the code initializes the 'brand' variable with the 'Apple', which you can see in the output. In this way, we can use the Nullish Coalescing operator while accessing the properties of objects having different properties.
🌐
TutorialsPoint
tutorialspoint.com › What-is-a-null-coalescing-operator-in-JavaScript
What is a "null coalescing" operator in JavaScript?
The object doesn't contain the 'brand' property, so the code initializes the 'brand' variable with the 'Apple', which you can see in the output. In this way, we can use the Nullish Coalescing operator while accessing the properties of objects having different properties.
🌐
Web Dev Simplified
blog.webdevsimplified.com › 2020-03 › javascript-null-coalesce
JavaScript Null Coalesce
Null coalesce is a new JavaScript language feature which makes assigning default values for null/undefined incredibly easy.
🌐
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
🌐
freeCodeCamp
freecodecamp.org › news › javascript-advanced-operators
Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment
January 4, 2024 - The Nullish Coalescing Operator can be used to safely access object properties and provide a default value when the property is missing: