Recall & Review
beginner
What does the nullish coalescing operator (??) do in TypeScript?
It returns the right-hand side value only if the left-hand side value is null or undefined; otherwise, it returns the left-hand side value.
Click to reveal answer
intermediate
How does nullish coalescing differ from the logical OR (||) operator?
Nullish coalescing (??) only treats null and undefined as empty, while || treats any falsy value (like 0, '', false) as empty.
Click to reveal answer
intermediate
Given: <pre>let value: string | null = null;<br>let result = value ?? 'default';</pre> What is the type of <code>result</code>?The type of
result is string because if value is null, the default string is used.Click to reveal answer
intermediate
Can nullish coalescing be chained with other operators in TypeScript? Give an example.
Yes. Example: <pre>let a: string | null = null;<br>let b: string | undefined = undefined;<br>let c = a ?? b ?? 'fallback';</pre> This returns the first defined and non-null value.Click to reveal answer
beginner
Why is nullish coalescing useful when working with optional or nullable types in TypeScript?
Because it safely provides a default value only when a variable is null or undefined, avoiding unintended fallback for falsy but valid values like 0 or empty string.
Click to reveal answer
What will
let x = 0 ?? 5; assign to x?✗ Incorrect
Since 0 is not null or undefined, the nullish coalescing operator returns 0.
Which values cause the right side of
?? to be used?✗ Incorrect
Only null and undefined trigger the right side value with ??.
What is the type of
let y: string | undefined = undefined; let z = y ?? 'hello';?✗ Incorrect
The result
z is always a string because if y is undefined, 'hello' is used.Which operator should you use to provide a default only when a value is null or undefined?
✗ Incorrect
The nullish coalescing operator ?? checks specifically for null or undefined.
What will
let a = false ?? true; assign to a?✗ Incorrect
False is not null or undefined, so the left value is used.
Explain how the nullish coalescing operator (??) works with nullable types in TypeScript.
Think about when you want to keep 0 or false but still provide a fallback for null or undefined.
You got /3 concepts.
Describe the difference between using || and ?? when assigning default values in TypeScript.
Consider what happens if your value is 0 or false.
You got /3 concepts.