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?"
Practice
condition ? expr1 : expr2 do in JavaScript?Solution
Step 1: Understand the ternary operator structure
The ternary operator has the formcondition ? expr1 : expr2. It checks thecondition.Step 2: Determine the returned value based on the condition
If theconditionis true, it returnsexpr1. Otherwise, it returnsexpr2.Final Answer:
Returns expr1 if condition is true, else expr2 -> Option DQuick Check:
condition ? expr1 : expr2 = expr1 or expr2 [OK]
- Thinking both expressions run always
- Confusing the order of expr1 and expr2
- Assuming it throws error on false condition
Solution
Step 1: Recall the ternary operator syntax
The correct syntax iscondition ? expr1 : expr2with a question mark and colon separating parts.Step 2: Check each option for correct punctuation
condition ? expr1 : expr2; matches the correct syntax. Options B, C, and D misuse commas, colons, or parentheses.Final Answer:
condition ? expr1 : expr2; -> Option AQuick Check:
Syntax is condition ? expr1 : expr2 [OK]
- Using commas instead of colon
- Swapping ? and :
- Adding unnecessary parentheses
const age = 20; const canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote);
Solution
Step 1: Evaluate the condition
Sinceage >= 18ageis 20, which is greater than or equal to 18, the condition is true.Step 2: Determine the value assigned to
Because the condition is true,canVotecanVoteis assigned the string 'Yes'.Final Answer:
'Yes' -> Option BQuick Check:
20 >= 18 ? 'Yes' : 'No' = 'Yes' [OK]
- Confusing true and false branches
- Thinking it returns boolean true/false
- Ignoring the condition value
let score = 85; let grade = score > 90 ? 'A' : score > 80 ? 'B' : 'C'; console.log(grade);
Solution
Step 1: Analyze the nested ternary expression
The expression uses nested ternary operators without parentheses, which is allowed in JavaScript.Step 2: Evaluate the condition with
First conditionscore = 85score > 90is false, so it checksscore > 80, which is true, sogradeis 'B'.Final Answer:
The code is correct and will output 'B'. -> Option AQuick Check:
Nested ternary without parentheses works [OK]
- Assuming nested ternary needs parentheses
- Thinking multiple ternaries are invalid syntax
- Confusing variable declaration errors
status based on a number score: if score is 0 or less, status should be 'Fail'; if between 1 and 50, 'Pass'; otherwise 'Excellent'. Which ternary expression correctly does this?Solution
Step 1: Understand the conditions for
statusscore <= 0means 'Fail', between 1 and 50 means 'Pass', and above 50 means 'Excellent'.Step 2: Check each option against these conditions
const status = score <= 0 ? 'Fail' : score <= 50 ? 'Pass' : 'Excellent'; correctly checksscore <= 0for 'Fail', thenscore <= 50for 'Pass', else 'Excellent'. Others have wrong ranges or conditions.Final Answer:
const status = score <= 0 ? 'Fail' : score <= 50 ? 'Pass' : 'Excellent'; -> Option CQuick Check:
Correct ranges and order in ternary [OK]
- Using wrong comparison operators
- Missing equal signs causing wrong ranges
- Incorrect order of conditions
Ready to prove it?
Pass the test and this pattern moves unknown
