Understanding ternary operator in JavaScript
Photo: Ternary Operator - ReactedNode
What you should know?
- Know what variables are in JavaScript.
- Understand boolean expressions (conditions that return true or false).
- Be familiar with if/else statements and what they do.
What you will learn
- What the ternary operator is in JavaScript.
- How to use it in place of if/else statements.
- How nested ternary operators work.
- When and how to use ternary operators properly.
- Why using it carelessly can reduce readability?
Key concepts
The ternary operator is a way to write an if/else statement in a single line.
Syntax:
The name "ternary" comes from the fact that it operates on three things (operands):
- A condition to check (evaluates to true or false).
- A value to return if the condition is true.
- A value to return if the condition is false.
Example:
Ternary operator in place of if/else
Ternary operators are shortcuts for simple if/else cases.
Now, let's achieve the same result using the ternary operator:
Nested Ternary Operators
A nested ternary is when you put a ternary inside another ternary.
Nesting can make code shorter but more complicated to read and understand.
Let's consider an if/else if/else
scenario:
Now, let's write the above code using nested ternary operator:
How to read this:
- If
score >= 90
? If yes, the grade is "A". - If not, is
score >= 80
? If yes, the grade is "B". - Else, the grade is "C".
Proper Use of ternary operators
As the grade example shows, even slightly nested ternary operators can become difficult to follow. Deeply nested ternaries are almost always a bad idea.
If a ternary operator makes you pause and figure out what it does, using a standard if/else
statement is better. Always prioritize clarity while writing code.
Use ternary when:
- You have a simple true/false condition.
- You want to assign a value based on a condition.
Why it matters
- The ternary operator helps you write cleaner, shorter code.
- It is an expression (produces a value) rather than a statement (performs an action) is key. Therefore, it fits naturally into assignments (variable = condition ? ...) or even function arguments.
- However, using it too much or for complex logic can make your code hard to read, understand, and debug. Writing readable code is more important than writing shorter code.