0
0
Javascriptprogramming~5 mins

If–else statement in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-else statement
O(1)
Understanding Time Complexity

Let's see how the time it takes to run an if-else statement changes as the input changes.

We want to know how many steps the program takes when it checks conditions.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkNumber(num) {
  if (num > 0) {
    return 'Positive';
  } else {
    return 'Non-positive';
  }
}
    

This code checks if a number is positive or not and returns a message.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if-else condition check.
  • How many times: Exactly once per function call.
How Execution Grows With Input

Checking one condition takes the same amount of time no matter what the input number is.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The time stays the same even if the input number changes.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same short time no matter what number you give it.

Common Mistake

[X] Wrong: "If-else takes longer when the number is bigger because it has to check more things."

[OK] Correct: The if-else only checks one condition once, so the size or value of the number does not change how long it takes.

Interview Connect

Understanding that simple condition checks run quickly helps you explain how your code handles decisions efficiently.

Self-Check

"What if we added a loop that runs the if-else check multiple times? How would the time complexity change?"