If–else statement in Javascript - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: A single if-else condition check.
- How many times: Exactly once per function call.
Checking one condition takes the same amount of time no matter what the input number is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The time stays the same even if the input number changes.
Time Complexity: O(1)
This means the program takes the same short time no matter what number you give it.
[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.
Understanding that simple condition checks run quickly helps you explain how your code handles decisions efficiently.
"What if we added a loop that runs the if-else check multiple times? How would the time complexity change?"