In TypeScript (and JavaScript), ??
is a syntax known as the Nullish Coalescing Operator. It is used to return the right operand when the left operand is null
or undefined
, otherwise it returns the left operand. This is particularly useful for handling values that may be null
or undefined
, especially when setting default values for variables.
Syntax:
let result = value1 ?? value2;
Example:
let name: string | null = null;
let defaultName = "Default Name";
let displayName = name ?? defaultName;
console.log(displayName); // Outputs "Default Name"
In this example, since name
is null
, displayName
will be assigned the value of defaultName
, which is "Default Name".
Difference from ||
:
Unlike the logical OR operator (||
), the Nullish Coalescing Operator only returns the right operand when the left operand is null
or undefined
, while the logical OR operator returns the right operand when the left operand is a falsy value (such as null
, undefined
, false
, 0
, NaN
, or ""
).
let value1 = 0;
let value2 = value1 || 10;
let value3 = value1 ?? 10;
console.log(value2); // Outputs 10, because 0 is considered a falsy value
console.log(value3); // Outputs 0, because 0 is not null or undefined
In this example, value2
is assigned 10
because value1
is a falsy value, while value3
is assigned 0
because value1
is not null
or undefined
.