Published on

Master JavaScript Ternary Operator With Examples

Authors
  • avatar
    Name
    Fadjar Irfan Rafi
    Twitter

The JavaScript ternary operator provides a concise way to write conditional statements. It's a powerful shorthand for if-else expressions that can make your code cleaner and more readable.

What is the Ternary Operator?

The ternary operator uses this syntax:

condition ? valueIfTrue : valueIfFalse

Let's compare traditional if-else with the ternary operator:

// Traditional if-else
let basket = 'apple'
if (basket === 'apple') {
  result = 'This basket has apples'
} else {
  result = 'This basket has no apples'
}

// Ternary operator
let basket = 'apple'
let result = basket === 'apple' ? 'This basket has apples' : 'This basket has no apples'

Best Practices for Using the Ternary Operator

  1. Use for Simple Conditions: Best suited for straightforward true/false decisions
  2. Keep it on One Line: When possible, write the entire expression on a single line
  3. Use Proper Spacing: Add spaces around operators for better readability

Nested Ternary Operators: When to Use Them

While you can nest ternary operators, it's generally discouraged for readability:

let basket = 'apple'
let result =
  basket === 'apple'
    ? 'This basket has apples'
    : basket === 'banana'
      ? 'This basket has bananas'
      : 'This basket has no fruit'

For multiple conditions, prefer using if-else statements or switch cases:

// Better approach for multiple conditions
if (basket === 'apple') {
  result = 'This basket has apples'
} else if (basket === 'banana') {
  result = 'This basket has bananas'
} else {
  result = 'This basket has no fruit'
}

When to Use the Ternary Operator

✅ Use ternary operators when:

  • You have a simple condition with two outcomes
  • The expression fits naturally on one line
  • You're assigning a value based on a condition

❌ Avoid ternary operators when:

  • You have multiple conditions to check
  • The logic is complex
  • The expression becomes difficult to read

Conclusion

The ternary operator is a powerful tool for writing concise conditional statements in JavaScript. While it shouldn't replace all if-else statements, it's perfect for simple conditions and can make your code more elegant when used appropriately.

Remember: clarity trumps brevity. If a ternary operator makes your code harder to understand, stick with traditional if-else statements.

Happy Coding! ✌️