Nullish coalescing
- TypeScript course
- Beginner
- Lesson 65/89
- 4 min
Learn default values with the ?? operator.
What is nullish coalescing?
Nullish coalescing (??) returns the right side when the left side is null or undefined; otherwise it keeps the left side. It is the safe way to provide a default value.
const userName: string | null = null;
const display = userName ?? "misafir";
console.log(display); // misafirValues like 0, false, or empty string are kept.
Difference between ?? and ||
Logical or (||) catches every falsy value: 0, "", false, null, undefined. Nullish coalescing (??) only provides a default for null and undefined. So when you want to keep valid values like 0 or empty string, prefer ??.
const n: number | null = 0;
console.log(n || 5); // 5 (0 is falsy)
console.log(n ?? 5); // 0 (only null/undefined)Practice Show a name with nullish coalescing
Write a function displayName(name: string | null | undefined): string. If name is null or undefined, return "Konuk"; otherwise uppercase name and return it. Print the result of all three calls.
Starter code
// displayName fonksiyonunu yaz
// parametre name: string, null veya undefined olabilir
// name null veya undefined ise "Konuk" döndür
// değilse name'i büyük harfe çevir ve döndürSample solution
function displayName(name: string | null | undefined): string {
return (name ?? "Konuk").toUpperCase();
}
console.log(displayName("ada"));
console.log(displayName(null));
console.log(displayName(undefined));Expected output
ADA KONUK KONUK
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does (n ?? 5) return when n is 0?
const n: number | null = 0;
console.log(n ?? 5);- returns 5
- returns 0 Correct answer
- returns undefined
- returns null
Explanation: Nullish coalescing (??) takes the right side only when the left is null or undefined. 0 is falsy but not null/undefined, so the left side is kept.
2 Complete the nullish coalescing operator
const display = userName ____ "misafir";
const display = userName ?? "misafir";
Explanation: Nullish coalescing ?? takes the right side when userName is null or undefined. || catches every falsy value, so it would also replace 0 or empty string; that is why it is wrong here.
3 Nullish coalescing parts
| Term | Meaning |
|---|---|
?? |
Default only for null/undefined |
|| |
Catches every falsy value |
userName ?? "misafir" |
Assigns a default name |
0 ?? 5 |
Returns 0 |