Arkar Myat

Double Question Marks (??) Explained in Typescript

May 4, 2023Arkar
Typescript

In TypeScript, the double question mark (??) is known as the nullish coalescing operator. It is used to provide a default value for a variable that may be null or undefined.

const userName: string | null = null;
const defaultName = "Guest";
const displayName = userName ?? defaultName;
console.log(displayName); // Output: "Guest"


const count: number | null = 0;
const defaultCount = 10;

const usingOr = count || defaultCount; // 10
const usingNullish = count ?? defaultCount; // 0

console.log(usingOr); // Output: 10
console.log(usingNullish); // Output: 0