0
0
Javascriptprogramming~5 mins

Else–if ladder in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Else-if ladder
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of conditions grows, the checks increase linearly if the match is near the end or missing.

Input Size (n)Approx. Operations
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows directly with the number of conditions.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a match grows in a straight line as you add more conditions.

Common Mistake

[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.

Interview Connect

Understanding how else-if ladders scale helps you write efficient condition checks and shows you can think about performance in everyday code.

Self-Check

"What if we replaced the else-if ladder with a switch statement? How would the time complexity change?"