Skip to main content

Ternary Operator

The ternary operator is used as a more syntactically concise replacement for the if ... else statement, when the same variable needs to be assigned different values according to a condition.

<condition> ? <expression_if_condition_true> : <expression_if_condition_false>

It works as follows:

  • condition evaluation.
  • If the condition is true, that is, converted to true, the expression after ? is evaluated.
  • If the condition is false, that is, converted to false, the expression after : is evaluated.
  • The value of the evaluated expression is returned as the result of the ternary operator.
let type;
const age = 20;

if (age >= 18) {
type = "adult";
} else {
type = "child";
}

console.log(type); // "adult"

Let's refactor by replacing if ... else with a ternary operator.

const age = 20;
const type = age >= 18 ? "adult" : "child";
console.log(type); // "adult"

Let's see how to find a bigger number.

const num1 = 5;
const num2 = 10;
let biggerNumber;

if (num1 > num2) {
biggerNumber = num1;
} else {
biggerNumber = num2;
}

console.log(biggerNumber); // 10

The code works correctly, we get the bigger number; however, this solution seems too lengthy considering how simple the problem is. Let's use a ternary operator.

const num1 = 5;
const num2 = 10;
const biggerNumber = num1 > num2 ? num1 : num2;

console.log(biggerNumber); // 10
Note

The ternary operator should be used in simple assignment or return operations. It is bad practice (anti-pattern) to use it to describe complex branches.