Ternary operator in Javascript - Time & Space Complexity
Let's see how the time it takes to run code with a ternary operator changes as input grows.
We want to know if using a ternary operator affects how long the program runs.
Analyze the time complexity of the following code snippet.
const checkNumber = (num) => {
return num > 0 ? "Positive" : "Non-positive";
};
const result = checkNumber(5);
console.log(result);
This code uses a ternary operator to decide if a number is positive or not.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison using the ternary operator.
- How many times: Exactly once per function call.
Each time we call the function, it does one quick check, no matter the number size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks if called 10 times |
| 100 | 100 checks if called 100 times |
| 1000 | 1000 checks if called 1000 times |
Pattern observation: The work grows directly with how many times the function runs, but each check is simple and quick.
Time Complexity: O(1)
This means the ternary operator runs in constant time, doing the same small amount of work no matter the input.
[X] Wrong: "The ternary operator takes longer if the number is bigger."
[OK] Correct: The ternary operator just checks a condition once, so the size of the number doesn't change how long it takes.
Understanding that simple operations like the ternary operator run quickly helps you explain your code clearly and confidently in interviews.
"What if we replaced the ternary operator with multiple if-else statements? How would the time complexity change?"