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_valueNote: 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.
function displayValue(input?: number) {
const value = input ?? 100;
console.log(value);
}
displayValue();
displayValue(50);
Output:
100
50Example 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.
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: 75Supported Browsers
The browsers supported by TypeScript Nullish Coalescing Operator are listed below:
- Google Chrome 5.0
- Edge 12
- Mozilla 4.0
- Safari 5.0
- Opera 11.1