If statement in Javascript - Time & Space Complexity
We want to see how the time it takes to run an if statement changes as the input changes.
Does the if statement make the program slower when input grows?
Analyze the time complexity of the following code snippet.
function checkNumber(num) {
if (num > 10) {
return "Greater";
} else {
return "Smaller or equal";
}
}
This code checks if a number is greater than 10 and returns a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if check (comparison).
- How many times: Exactly once per function call.
The if statement runs once no matter what the input number is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same even if the input number changes.
Time Complexity: O(1)
This means the if statement takes the same amount of time no matter how big or small the input is.
[X] Wrong: "If statements take longer when the input number is bigger."
[OK] Correct: The if check is just one comparison and does not repeat or grow with input size.
Understanding that simple if statements run in constant time helps you explain how your code behaves clearly and confidently.
"What if we added a loop inside the if statement? How would the time complexity change?"