3 Example(s) of JavaScript if condition


Description :

JavaScript if condition is used to execute a statement if the condition is true, In our example, if the age is less than 18 then "You are not qualified for Voting" message will be displayed else "You are qualified for Voting" message will be displayed. See the code snippet for JavaScript If condition:


JavaScript if condition Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>   
<body>
<button onclick="dayGreeting()">Show the message</button>
<p id="sample"></p>
<script>
function dayGreeting() {
    var age = 19 
    var message;
    if (age < 18) {
        message = "You are not qualified for Voting";
    } else {
        message = "You are qualified for Voting";
    }
    document.getElementById("sample").innerHTML = message;
}
</script>
</body>
</html>

Output

Description :

In this example, We have a flag variable with true as its value. 

var flag= true; if(flag){ document.write("flag is true."); }

 It will return "flag is true" statement.


JavaScript if condition Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>   
<body>
<script>
var flag= true;
      
if(flag){
document.write("<b>flag is true.</b>");
 }
 
 </script>
</body>
</html>

Output

Description :

if the variable book is "maths" then it will print as "Maths Book",  following condition will execute

else if( book == "maths" ){ document.write("Maths Book"); } 



JavaScript if condition Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>   
<body>
<script>
        
var book = "maths";

if( book == "history" ){
document.write("<b>History Book</b>");
}
else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}         
else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}         
else{
document.write("<b>Unknown Book</b>");
}
</script>
</body>
</html>

Output