How to Use the Nested Ternary Operator in JavaScript?

Estimated read time 2 min read

A ternary operator in JavaScript is a shorthand way of writing an if-else statement. It’s called a ternary operator because it takes three operands: a condition, a result for when the condition is truthy, and a result for when the condition is falsy.

Here’s an example of a simple ternary operator in JavaScript:

var age = 25;
var canDrink = (age >= 21) ? "Yes" : "No";
console.log(canDrink); // Output: "Yes"

In the example above, the ternary operator evaluates the condition age >= 21 and returns the string “Yes” if the condition is truthy, and “No” if the condition is falsy.

A nested ternary operator is simply a ternary operator within another ternary operator. Here’s an example:

var age = 25;
var canDrink = (age >= 21) ? "Yes" : (age >= 18) ? "Maybe" : "No";
console.log(canDrink); // Output: "Yes"

In the example above, the first ternary operator checks if age >= 21 and returns “Yes” if the condition is truthy. If the first condition is falsy, then the second ternary operator is evaluated. This second ternary operator checks if age >= 18 and returns “Maybe” if the condition is truthy. If the second condition is falsy, then the string “No” is returned.

It’s important to note that nested ternary operators can become difficult to read, especially for complex conditions. If you find yourself using nested ternary operators, it may be a good idea to consider refactoring your code to use if-else statements instead.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply