Example

Conditional operator

HTML

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
    <title>Conditional operator</title>
</head>
<body>
<!--
    Conditional operator also called ternary operator
    It assigns a value to a variable based on some condition (true or false).
        Syntax :
        variableName = (condition) ? valueOne : valueTwo 
-->

    <h1>Demo: Conditional operator</h1>    

    <h2>Is the citizen eligible to vote ?</h2>
    <p id="para"></p>

    <!-- JavaScript code Starts here -->
    <script>

        /************************************************/
        // JavaScript Conditional (Ternary) Operator
        // Example to demo voting rights eligibility
        //
        let age = 24;    // Actual Age
        let eligibleAge = 18
        let votingRights;
        votingRights = (age > eligibleAge) ? "eligible to vote!" : "NOT eligible to vote!";
        document.getElementById('para').innerHTML =
            "Age of the citizen is " + 
            age + 
            " years. " +
            "Hence, citizen is " + 
            votingRights;

    </script>
    <!-- JavaScript code Ends here -->

</body>
</html>
                    

Output

View original