0
0
Javascriptprogramming~5 mins

Ternary operator in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Ternary operator
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we call the function, it does one quick check, no matter the number size.

Input Size (n)Approx. Operations
1010 checks if called 10 times
100100 checks if called 100 times
10001000 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.

Final Time Complexity

Time Complexity: O(1)

This means the ternary operator runs in constant time, doing the same small amount of work no matter the input.

Common Mistake

[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.

Interview Connect

Understanding that simple operations like the ternary operator run quickly helps you explain your code clearly and confidently in interviews.

Self-Check

"What if we replaced the ternary operator with multiple if-else statements? How would the time complexity change?"