Nullish coalescing with types in Typescript - Time & Space Complexity
We want to understand how fast code runs when using nullish coalescing with types in TypeScript.
Specifically, how does the number of steps change as input size grows?
Analyze the time complexity of the following code snippet.
function getValue(input: string | null | undefined): string {
return input ?? "default";
}
const results = [];
for (let i = 0; i < n; i++) {
results.push(getValue(null));
}
This code uses nullish coalescing to provide a default string when input is null or undefined, repeated n times.
- Primary operation: The loop runs n times, calling getValue each time.
- How many times: Exactly n times, where n is the input size.
Each call to getValue is very fast and constant time, but we do it n times in the loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 simple checks and returns |
| 100 | 100 simple checks and returns |
| 1000 | 1000 simple checks and returns |
Pattern observation: The total work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Nullish coalescing makes the code run instantly regardless of input size."
[OK] Correct: Even though each check is quick, doing it many times adds up linearly with input size.
Understanding how simple operations inside loops add up helps you explain performance clearly in interviews.
"What if we replaced the loop with a recursive call that processes the input n times? How would the time complexity change?"
Practice
What does the nullish coalescing operator ?? do in TypeScript?
Solution
Step 1: Understand nullish coalescing behavior
The operator??checks if the left value isnullorundefined.Step 2: Determine when right value is returned
If the left value isnullorundefined, it returns the right value; otherwise, it returns the left value.Final Answer:
Returns the right value only if the left value is null or undefined. -> Option DQuick Check:
Null or undefined triggers right value [OK]
- Confusing with || operator that checks all falsy values
- Thinking 0 or empty string triggers right value
- Assuming it throws errors on null or undefined
Which of the following is the correct syntax to use nullish coalescing in TypeScript?
const value = input ?? 'default';
Solution
Step 1: Identify correct nullish coalescing syntax
The operator??is used between two values to provide a fallback if the left is null or undefined.Step 2: Check each option
const value = input ?? 'default';:const value = input ?? 'default';uses??correctly. const value = input ? 'default' : input; uses ternary, const value = input ??= 'default'; uses nullish assignment??=, const value = input || 'default'; uses logical OR.Final Answer:
const value = input ?? 'default'; -> Option AQuick Check:
Correct nullish coalescing syntax uses ?? [OK]
- Using || which treats 0 or empty string as false
- Confusing with ternary operator syntax
- Using invalid operators like ??=
What is the output of this TypeScript code?
let name: string | null = ""; const displayName = name ?? "Guest"; console.log(displayName);
Solution
Step 1: Check the value of
The variablenamenameis an empty string "", which is NOT null or undefined.Step 2: Apply nullish coalescing operator
Sincenameis not null or undefined,name ?? "Guest"returns the left value, which is "" (empty string).Final Answer:
"" (empty string) -> Option CQuick Check:
Empty string is not nullish, so left value stays [OK]
- Assuming empty string triggers right side
- Confusing ?? with || operator
- Expecting 'Guest' instead of empty string
Identify the error in this TypeScript code using nullish coalescing:
let count: number | undefined = 0; const result = count ?? 10; console.log(result);
Solution
Step 1: Analyze the value of
The variablecountcountis 0, which is NOT null or undefined.Step 2: Apply nullish coalescing operator
Sincecountis 0 (a valid number),count ?? 10returns 0, no error occurs.Final Answer:
No error; output is 0 -> Option BQuick Check:
0 is not nullish, so left value returned [OK]
- Thinking 0 triggers right side fallback
- Believing ?? cannot be used with numbers
- Confusing ?? with || operator
You have a function that accepts an optional string parameter input. You want to return input if it is not null or undefined, but if it is, return the string "No input". Which is the best way to write this using nullish coalescing?
function getInput(input?: string): string {
// Fill in the return statement
}Solution
Step 1: Understand the requirement
Returninputif it is NOT null or undefined; otherwise, return "No input".Step 2: Choose the best nullish coalescing usage
input ?? "No input"returnsinputif it is not nullish, else "No input". This is concise and clear.Final Answer:
return input ?? "No input"; -> Option AQuick Check:
?? returns left unless null/undefined [OK]
- Using || which treats empty string as false
- Using ternary unnecessarily
- Checking null and undefined manually instead of ??
Ready to prove it?
Pass the test and this pattern moves unknown
