Skip to content

JavaScript conditional operator | Example code

  • by

JavaScript conditional operator is assigned a value to a variable based on some condition. It’s the only JavaScript operator that takes three operands. It also called a ternary operator.

Syntax of conditional operator in JS.

condition ? exprIfTrue : exprIfFalse

JavaScript conditional operator Example

Let’s see simple HTML example code for a given condition – If the value is above 30 then pass else fail.

<!DOCTYPE html>
<html>

<body>
    <script type="text/javascript">
        var marks = 80;
        var result = (marks >= 80) ? "Pass" : "Failed";
        console.log(result); 

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

Output:

JavaScript conditional operator HTML example code

Do comment if you have any doubts and suggestions on this 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

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