Open In App

Nullish Coalescing Operator (??) in TypeScript

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. This operator is useful for assigning default values to variables, ensuring more consistent and predictable code execution.

Syntax

The Nullish Coalescing Operator is represented by two adjacent question marks (?? ):

variable ?? default_value

Note: At its core, the operator will return default_value when the variable is either null or undefined, alternatively it will return the actual variable.

Example 1: Using Nullish Coalescing Operator in a Function

In the given below example we are demonstrating the use of the Nullish Coalescing Operator within a function.

JavaScript
function displayValue(input?: number) {
    const value = input ?? 100;
    console.log(value);
}

displayValue(); 
displayValue(50);

Output:

100
50

Example 2: Setting Default Values in Objects

In the given below example the Nullish Coalescing Operator is used for setting default values for properties in objects, especially when dealing with JSON data.

JavaScript
interface Settings {
    volume?: number;
    brightness?: number;
}

const userSettings: Settings = {
    volume: 0
};

const volume = userSettings.volume ?? 50;
const brightness = userSettings.brightness ?? 75;

console.log(`Volume: ${volume}`);         
console.log(`Brightness: ${brightness}`);

Output:

Volume: 0
Brightness: 75

Supported Browsers

The browsers supported by TypeScript Nullish Coalescing Operator are listed below:


Next Article

Similar Reads