Loading

If Statement

  • In JavaScript, an if statement allows you to execute a block of code if a specified condition is true, and optionally execute a different block of code if the condition is false. 

There are  three types of if statements:

  • if statement
  • if else statement
  • if else if statement

if statement:

  • if an expression is true it evaluates content only.

Syntax:

if (condition) {
   // Code to be executed if the condition is true
}

Flow chart:

Example:

<html>
<body>
   <script>
      var a = 20;
      if (a % 2 == 0) {
         document.write("a is even number");
      }
      else {
         document.write("a is odd number");
      }  
   </script>
</body>
</html>

Output:

a is an even number


If else statement:

  • If the condition is true then the if block will execute and if false then the else block will execute

Syntax:

if(expression){  
// if condition is true  
}  
else{  
//content to be evaluated if condition is false  
}  

Flow chart:

Example:

<html>
<body>
   <script>
      var a = 20;
      if (a % 2 == 0) {
         document.write("a is even number");
      }
      else {
         document.write("a is odd number");
      }  
   </script>
</body>
</html>

if else if statement:

  • if else if evaluates the content if the expression is true from several expressions.

Syntax:

if(expression1){  
//content to be evaluated if expression1 is true  
}  
else if(expression2){  
//content to be evaluated if expression2 is true  
}  
else if(expression3){  
//content to be evaluated if expression3 is true  
}  
else{  
//content to be evaluated if no expression is true  
}  

Example:

<html>
<body>
<script>  
var a=20;  
if(a==10){  
document.write("a is equal to 10");  
}  
else if(a==15){  
document.write("a is equal to 15");  
}  
else if(a==20){  
document.write("a is equal to 20");  
}  
else{  
document.write("a is not equal to 10, 15 or 20");  
}  
</script>  
</body>
</html>

Output:

a is equal to 20