How to Use the JavaScript Nested Ternary Operator

As you might know, ternary operators in JavaScript are a single statement alternative to if...else statements frequently used to make code more concise and easier to understand. For example, we could have a function that returns “yes” or “no” depending on whether a number passed to it is odd or not.

function isOdd(num) { if (num % 2 === 1) return 'yes'; else return 'no'; }

We can refactor the isOdd function to use a one-line conditional statement like this:

function isOdd(num) { return num % 2 === 1 ? 'yes' : 'no'; }

Subscribe to Coding Beauty Newsletter

Gain useful insights and advance your web development knowledge with weekly tips and tutorials from Coding Beauty. Over 2,000 developers subscribe.

Nested ternary operator in JavaScript

We can nest a ternary operator as an expression inside another ternary operator. We can use this to replace if…else if…else statements and switch statements. For example, we could have a piece of code that sets the English word for the numbers 1, 2, and 3 to a variable. With if...else:

let num = 1; let word; if (num === 1) word = 'one'; else if (num === 2) word = 'two'; else if (num === 3) word = 'three'; else num = 'unknown';


let num = 1; let word; switch (num) { case 1: word = 'one'; break; case 2: word = 'two'; break; case 3: word = 'three'; break; default: word = 'unknown'; break; }

And now with nested ternary operators:

let num = 1; let word = num === 1 ? 'one' : num === 2 ? 'two' : num === 3 ? 'three' : 'unknown';

The above code example works exactly like the previous two and is less cluttered. Notice we are now able to declare and set the variable in the same statement with this nested ternary approach.

11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *