Skip to content

Ternary operator multiple conditions JavaScript | Example code

  • by

Ternary operator more than one condition is possible with nesting it. Let’s see example for that in this tutorial.

Example of Ternary operator multiple conditions JavaScript

HTML example code for

If mark -> 1 then result = A

If mark -> 2 then result = B

else result = C

<!DOCTYPE html>
<html>

<body>
    <script type="text/javascript">
        var marks = 8;
        
        var result = (marks == 1) ? "A" : (marks == 2) ? "B" : "C";

        console.log(result); 

    </script>
</body>
</html>

Output:

HTML Ternary operator multiple conditions JavaScript

JS Ternary functions with multiple conditions

Same code with function to easy use. This version to be fairly readable

<!DOCTYPE html>
<html>

<body>
    <script type="text/javascript">
        function foo(bar){
            var res= bar === 'a' ? 1 : 
            bar === 'b' ? 2 : 3; 

            return res;
        }

        console.log(foo("a")); 

    </script>
</body>
</html>

Output: 1

Another Example for better understanding

Multiple conditions ternary operator JavaScript function.

<!DOCTYPE html>
<html>

<body>
    <script type="text/javascript">
     function checkSign(num) {

        return num > 0 ? "positive" : num < 0 ? "negative" : "zero";

    }

    console.log(checkSign(10));
    console.log(checkSign(-10));
    console.log(checkSign(0));

</script>
</body>
</html>

Output:

Multiple conditions ternary operator JavaScript function

Do comment if you have any doubts and suggestion on this question based topic.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading