0
0
Javascriptprogramming~5 mins

Nested conditional statements in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested conditional statements
O(1)
Understanding Time Complexity

We want to see how the time it takes to run nested conditional statements changes as input changes.

Specifically, we ask: does adding more conditions make the program slower as inputs grow?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkNumber(num) {
  if (num > 0) {
    if (num % 2 === 0) {
      return 'Positive even';
    } else {
      return 'Positive odd';
    }
  } else {
    return 'Non-positive';
  }
}
    

This code checks if a number is positive and then if it is even or odd.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps; only simple checks.
  • How many times: Each condition runs once per function call.
How Execution Grows With Input

The time to run this code does not increase when the input number gets bigger.

Input Size (n)Approx. Operations
103 checks
1003 checks
10003 checks

Pattern observation: The number of steps stays the same no matter the input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays constant no matter how big the input is.

Common Mistake

[X] Wrong: "More conditions always make the program slower as input grows."

[OK] Correct: Nested conditions run only once per input, so they do not slow down with bigger inputs.

Interview Connect

Understanding that nested conditions do not add time with bigger inputs helps you explain code efficiency clearly and confidently.

Self-Check

"What if we added a loop inside the nested conditions? How would the time complexity change?"