The nullish coalescing operator DOES NOT apply to this case:

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.

See the docs

In this case you have a simple union of type Day | 0, you just have to check manually:

for (let i = 0; i < 4; i++) {
  const item = daysArray[i];

  if (typeof item === "number") {
    console.log(0);
  } else {
    console.log(item.dayNumber);
  }
} 
Answer from Nullndr on Stack Overflow
🌐
TypeScript
typescriptlang.org › play › 3-7 › syntax-and-messaging › nullish-coalescing.ts.html
TypeScript: Playground Example - Nullish Coalescing
The nullish coalescing operator is an alternative to || which returns the right-side expression if the left-side is null or undefined. In contrast, || uses falsy checks, meaning an empty string or the number 0 would be considered 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 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.
Top answer
1 of 4
1

The nullish coalescing operator DOES NOT apply to this case:

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.

See the docs

In this case you have a simple union of type Day | 0, you just have to check manually:

for (let i = 0; i < 4; i++) {
  const item = daysArray[i];

  if (typeof item === "number") {
    console.log(0);
  } else {
    console.log(item.dayNumber);
  }
} 
2 of 4
1

The nullish coalescing does not apply in this case, here is documentation of nullish coalescing with examples of how it's supposed to be used: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing

The reason why your code is giving red squiggly is because the element at daysArray[i] might be either a number or an object which has the shape of the Day interface. so trying to access daysArray[i].dayNumber is not entirely correct, first you have to check that it's an object and not a number. this way typescript compiler will infer the type of daysArray[i] to be of type Day and will allow you to access dayNumber property.

Here is a working example:

type Day = {
  dayNumber: number;
  color: string;
  isBooked: boolean;
};

const myDay: Day = {
  dayNumber: 12,
  color: "blue",
  isBooked: false
};

const daysArray: (Day | 0)[] = [0, 0, 0, myDay];

for (let i = 0; i < daysArray.length; i++) {
  const element = daysArray[i];
  if(typeof element === 'object') {
    console.log(element.dayNumber);
  }
}

Please refer to the official documentation for type narrowing: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards

🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-3-7.html
TypeScript: Documentation - TypeScript 3.7
The nullish coalescing operator is another upcoming ECMAScript feature that goes hand-in-hand with optional chaining, and which our team has been involved with championing in TC39.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › nullish-coalescing-operator-in-typescript
Nullish Coalescing Operator (??) in TypeScript - GeeksforGeeks
July 23, 2025 - The nullish coalescing (??) operator is a logical operator in TypeScript that returns its right-hand side operand if the left-hand side operand is null or undefined; otherwise, it returns the left-hand side operand.
🌐
TypeScript ESlint
typescript-eslint.io › rules › prefer-nullish-coalescing
prefer-nullish-coalescing | typescript-eslint
Because the nullish coalescing operator only coalesces when the original value is null or undefined, it is much safer than relying upon logical OR operator chaining ||, which coalesces on any falsy value.
🌐
Marius Schulz
mariusschulz.com › blog › nullish-coalescing-the-operator-in-typescript
Nullish Coalescing: The ?? Operator in TypeScript — Marius Schulz
August 14, 2021 - TypeScript 3.7 added support for the ?? operator, which is known as the nullish coalescing operator. We can use this operator to provide a fallback value for a value that might be null or undefined.
Find elsewhere
🌐
Reddit
reddit.com › r/typescript › nullish coalescing operator vs logical or
r/typescript on Reddit: Nullish Coalescing Operator vs Logical OR
July 13, 2022 -

Take this interface for example

interface Item {
  value?: number
}

Which among the two do you prefer if you will be accessing the value property of an item and why?

console.log(item.value ?? 1.00) // 1.00 is the fallback value
console.log(item.value || 1.00) // 1.00 is the fallback value

Personally, I prefer to use the nullish coalescing operator ?? for fallback values since it's more explicit and it sames me from the weird falsy values that JavaScript has.

🌐
Execute Program
executeprogram.com › courses › everyday-typescript › lessons › nullish-coalescing
Everyday TypeScript: Nullish Coalescing
Learn programming languages like TypeScript, Python, JavaScript, SQL, and regular expressions. Interactive with real code examples.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 26578
Nullish coalescing operator (??) · Issue #26578 · microsoft/TypeScript
May 28, 2018 - export interface Configuration { // Default: "(no name)"; empty string IS valid name?: string; // Default: -1; 0 is valid items?: number; // Default: true active?: boolean; } function configureSomething(config: Configuration) { // With null-coalescing operator config.name = config.name ??
Published   Aug 21, 2018
🌐
LogRocket
blog.logrocket.com › home › optional chaining and nullish coalescing in typescript
Optional chaining and nullish coalescing in TypeScript - LogRocket Blog
June 4, 2024 - It was introduced in TypeScript 3.7 with the ?. operator. Optional chaining is often used together with nullish coalescing, which is the ability to fall back to a default value when the primary expression evaluates to null or undefined.
🌐
Codeisbae
codeisbae.com › typescript-optional-chaining-nullish-coalescing
Optional Chaining and Nullish Coalescing in TypeScript | Code Is Bae
The code snippets above illustrate that the Nullish Coalescing Operator comes into play specifically for nullish values, not boolean or other data types.
🌐
Medium
medium.com › @ambily_francis › unlocking-typescripts-nullish-coalescing-d00ef1db698a
Unlocking TypeScript’s Nullish Coalescing | by Ambily Francis | Medium
March 11, 2024 - Nullish coalescing is a feature introduced in TypeScript to handle scenarios where you want to provide a default value for a variable or expression if its current value is either `null` or `undefined`. This concept is represented by the `??` ...
Top answer
1 of 15
428

Yes. As of TypeScript 3.7 (released on November 5, 2019), this feature is supported and is called Optional Chaining:

At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined. The star of the show in optional chaining is the new ?. operator for optional property accesses.

Refer to the TypeScript 3.7 release notes for more details.


Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as Issue #16 on the TypeScript repo (dating back to 2014).

As far as what to call this operator, there doesn't appear to be a consensus. In addition to "optional chaining" (which is also what it's called in JavaScript and Swift), there are a couple of other examples:

  • CoffeeScript refers to it as the existential operator (specifically, the "accessor variant" of the existential operator):

The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined.

  • C# calls this a null-conditional operator.

a null-conditional operator applies a member access, ?., or element access, ?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returns null.

  • Kotlin refers to it as the safe call operator.

There are probably lots of other examples, too.

2 of 15
157

It is now possible, see answer of user "Donut".

Old answer: Standard JavaScript behaviour regarding boolean operators has something that may help. The boolean methods do not return true or false when comparing objects, but in case of OR the first value that is equal to true.

Not as nice as a single ?, but it works:

var thing = foo && foo.bar || null;

You can use as many && as you like:

var thing = foo && foo.bar && foo.bar.check && foo.bar.check.x || null;

Default values are also possible:

var name = person && person.name || "Unknown user";
🌐
egghead.io
egghead.io › lessons › typescript-use-the-nullish-coalescing-operator-in-typescript
Create a serverless API with Ampt and TypeScript | egghead.io
Use the Optional Chaining Operator in TypeScript · 7m 13s · 2 · Use the Nullish Coalescing Operator in TypeScript · 5m 7s · 3 · Statically Type Unknown Values with TypeScript's unknown Type · 7m 12s · 4 · Narrow the unknown Type with TypeScript's Assertion Functions ·
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.

🌐
GitHub
github.com › microsoft › TypeScript › issues › 48536
Nullish coalescing and conditional type narrowing · Issue #48536 · microsoft/TypeScript
April 3, 2022 - Conditional type narrowing through the || operator + the use of the nullish coalescing operator should understand each other to reify the type correctly. declare function foo(): string | undefined const a = foo() const b = foo() if (a != undefined || b != undefined) { const c = a ?? b } c should have type string but instead it has type string | undefined because TS hasn't reasoned that the only way into the block is if a ?? b must be non-null.
Published   Apr 03, 2022