Challenge - 5 Problems
Nullish Coalescing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this code using nullish coalescing?
Consider the following TypeScript code snippet. What will be logged to the console?
Typescript
const value: string | null = null; const result = value ?? "default"; console.log(result);
Attempts:
2 left
💡 Hint
Remember that nullish coalescing returns the right side only if the left side is null or undefined.
✗ Incorrect
The variable 'value' is null, so the nullish coalescing operator '??' returns the right side, which is the string "default".
❓ Predict Output
intermediate2:00remaining
What is the output when using nullish coalescing with undefined?
Analyze this TypeScript code. What will be printed?
Typescript
let input: number | undefined = undefined; const output = input ?? 42; console.log(output);
Attempts:
2 left
💡 Hint
Nullish coalescing treats undefined as nullish and returns the right side.
✗ Incorrect
Since 'input' is undefined, the expression 'input ?? 42' evaluates to 42.
❓ Predict Output
advanced2:00remaining
What is the output when nullish coalescing is combined with a falsy value 0?
Look at this TypeScript code. What will be logged to the console?
Typescript
const count: number | null = 0; const result = count ?? 10; console.log(result);
Attempts:
2 left
💡 Hint
Nullish coalescing only treats null or undefined as nullish, not other falsy values like 0.
✗ Incorrect
The variable 'count' is 0, which is falsy but not null or undefined, so 'count ?? 10' returns 0.
❓ Predict Output
advanced2:00remaining
What is the type of the variable after nullish coalescing with union types?
Given this TypeScript code, what is the type of 'finalValue'?
Typescript
type Input = string | null | undefined; const input: Input = null; const finalValue = input ?? "fallback";
Attempts:
2 left
💡 Hint
Nullish coalescing narrows the type by removing null and undefined from the left side.
✗ Incorrect
Since 'input' can be string, null, or undefined, and nullish coalescing replaces null or undefined with a string, 'finalValue' is always a string.
🧠 Conceptual
expert2:00remaining
Which option correctly explains the difference between || and ?? operators in TypeScript?
Choose the best explanation about how the logical OR (||) operator differs from the nullish coalescing (??) operator in TypeScript.
Attempts:
2 left
💡 Hint
Think about how 0 or empty string are treated by each operator.
✗ Incorrect
The || operator returns the right side if the left side is any falsy value (0, '', null, undefined), while ?? only returns the right side if the left side is null or undefined.