4) Conditionals, Loops and Functions Lesson

The JavaScript Ternary Operator

3 min to complete · By Ian Currie

The ternary operator is a single-line alternative to writing if...else statements. They evaluate a condition and return one of two values based on whether the condition is true or false.

When to Use the Ternary Operator

Ternary operators are a great way to make your code more compact and avoid repetition. They are most appropriate when handling single conditions and straightforward expressions but lose their appeal when dealing with more complex conditions and actions due to it's readability.

## How to Use the Ternary Operator

Ternary operators are written on a single line and have three crucial components to a ternary operator:

  1. The condition
  2. The expression to be executed if the condition returns true
  3. The expression to be executed if the condition returns false

There are two symbols that link our components together:

  1. The ? symbol which separates the conditions from the expressions
  2. And the : symbol which separates the two conditions

This is what the general syntax of a ternary operator looks like:

condition ? expressionIfTrue : expressionIfFalse;

Ternary Operator Example

Here is an example using a regular if...else statement:

const number = 10;

let result;

if (number % 2 === 0) {
  result = "even";
} else {
  result = "odd";
}

console.log(`The number ${number} is ${result}.`);

Here is how you could write it using a ternary operator:

const number = 10;

const result = number % 2 === 0 ? "even" : "odd";

console.log(`The number ${number} is ${result}.`);

Notice how the second example provides a more concise way of writing a conditional statement while still achieving the same result. This is a good example of a scenario in which the ternary operator could be preferred over the more verbose if ... else block.

## Summary: What is the JavaScript Ternary Operator

  • A ternary operator is a concise way of writing conditional statements
  • They are useful when handling single conditions and straightforward expressions
  • You should not replace if...else statements with ternary operators when dealing with complex conditions

How to Use the Ternary Operator

  • Ternary operators are typically written on a single line

  • This is what the general syntax of a ternary operator looks like:

    condition ? expressionIfTrue : expressionIfFalse;