3 Example(s) of JavaScript Conditional operators


Description :

Conditional Operator ? will return the first value if condition is true else second value.


JavaScript Conditional operators Example - 1
<!DOCTYPE html>
<html>
 <head>
 <title>Welcome to LearnKode - A code learning platform</title>
</head>
  <body>
<input ype="text" id="age"/>
<button onclick="voteableAge()">Check eligible for voting</button>
<p id="sample"></p>
<script>
function voteableAge() {
    var age, voteable;
    age = document.getElementById("age").value;
    voteable = (age < 18) ? "Too young":"Old enough";
    document.getElementById("sample").innerHTML = voteable + " to vote.";
}
</script>
      </body>
</html>

Output

Description :

Conditional Operator ? with multiple conditions.


JavaScript Conditional operators Example - 2
<!DOCTYPE html>
<html>
 <head>
 <title>Welcome to LearnKode - A code learning platform</title>
</head>
  <body>
<p id="sample"></p>
<script>
   var firstCheck = false,
    secondCheck = false,
    access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
    document.getElementById("sample").innerHTML = access;

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

Output

Description :

Conditional Operator ? with > operator


JavaScript Conditional operators Example - 3
<!DOCTYPE html>
<html>
 <head>
 <title>Welcome to LearnKode - A code learning platform</title>
</head>
  <body>
 <script>
            var a = 10;
            var b = 20;
            var linebreak = "<br />";
         
            document.write ("((a > b) ? 100 : 200) => ");
            result = (a > b) ? 100 : 200;
            document.write(result);
            document.write(linebreak);
         
            document.write ("((a < b) ? 100 : 200) => ");
            result = (a < b) ? 100 : 200;
            document.write(result);
            document.write(linebreak);
        
      </script>
      </body>
</html>

Output