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?"