Else–if ladder in Javascript - Time & Space Complexity
We want to understand how the time taken by an else-if ladder changes as we add more conditions.
How does checking multiple conditions one after another affect performance?
Analyze the time complexity of the following code snippet.
function checkNumber(num) {
if (num === 1) {
return 'One';
} else if (num === 2) {
return 'Two';
} else if (num === 3) {
return 'Three';
} else {
return 'Other';
}
}
This code checks a number against several conditions one by one until it finds a match.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions one after another in the else-if ladder.
- How many times: Up to the number of conditions, until one matches or all are checked.
As the number of conditions grows, the checks increase linearly if the match is near the end or missing.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of conditions.
Time Complexity: O(n)
This means the time to find a match grows in a straight line as you add more conditions.
[X] Wrong: "Else-if ladders always run in constant time because they stop once a match is found."
[OK] Correct: If the match is near the end or missing, many conditions are checked, so time grows with the number of conditions.
Understanding how else-if ladders scale helps you write efficient condition checks and shows you can think about performance in everyday code.
"What if we replaced the else-if ladder with a switch statement? How would the time complexity change?"