Ternary Operators in JavaScript: A Simple Guide

Today, we will dive into a concise and neat way to perform conditional (if-else like) operations in your JavaScript code using the ternary operator.

What is a Ternary Operator?

A ternary operator is a shorthand method for writing a simple if-else statement.

Image that reads: "ternary, is an adjective, which means composed of three parts."

It takes three operands, hence the name "ternary". The syntax is:

condition ? expression1 : expression2

Here's how it works:

  • If the condition is true, expression1 is executed.
  • If the condition is false, expression2 is executed.


Consider the following scenario:

You want to determine if a number is even or odd.

Using traditional "if-else":

let number = 5;
let result;

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

console.log(result);  // Outputs: odd

Using the ternary operator:

let number = 5;
let result = (number % 2 === 0) ? 'even' : 'odd';

console.log(result);  // Outputs: odd

See how much more concise that is?

Nested Ternaries

While you can nest ternary operators, be cautious, as it can make the code less readable.

Here's a simple example to show how it works:

let number = 0;
let result = (number > 0) ? 'positive' : (number < 0) ? 'negative' : 'zero';

console.log(result);  // Outputs: zero

Pro Tips 🤖

  1. Readability over brevity: While ternaries can shorten your code, don't sacrifice readability. If a condition gets too complex, it might be better to use the traditional if-else approach.
  2. Avoid deep nesting: As shown above, you can nest ternaries, but doing so excessively can make your code hard to understand. This again to do with readability. Remeber you write code for humans not machines. It usually gets minified anyway!
  3. Commenting: If you think a ternary might be confusing to others (or even future you), add a brief comment explaining its purpose.

Happy coding! 🦄

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.