Skip to content

Nested ternary operator JavaScript | Example code

  • by

You can nest one ternary operator as an expression inside another ternary operator to work as a Nested ternary operator in JavaScript.

Nested ternary operator JavaScript

Simple example code program to check if the number is positive, negative, or zero.

<!DOCTYPE html>
<html>
<body>

  <script type="text/javascript">
   let n = 100;

   let result = (n >= 0) ? (n == 0 ? "zero" : "positive") : "negative";

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

 </script>

</body>
</html>

Output:

Nested ternary operator JavaScript

Note: It’s hard to read nested ternary operators, You should try to avoid it.

Alternative to the nested ternary operator in JS

If else is alternatives here are basically:

  1. That if/else you don’t want to do
  2. A switch combined with if/else
if (res.distance == 0) {
    word = 'a';
} else if (res.distance == 1 && res.difference > 3) {
    word = 'b';
} else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) {
    word = 'c';
} else {
    word = 'd';
}

case statements can be expressions, and are matched against the switch value in source code order:

switch (true) {
    case res.distance == 0:
        word = 'a';
        break;
    case res.distance == 1 && res.difference > 3:
        word = 'b';
        break;
    case res.distance == 2 && res.difference > 5 && String(res.key).length > 5:
        word = 'c';
        break;
    default:
        word = 'd';
        break;
}

Do comment if you have any doubts or suggestions on this JS ternary operator.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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