Javascript If-else

These conditional statement is used to execute the code whether condition is true or false. There are three forms of if statement in JavaScript:-

  • If Statement
  • If else statement
  • if else if statement

If statement

This type of statement evaluates to execute a block of Javascript code if a condition is true.

Syntax:-
if (condition) {
  //  block of code to be executed if the condition is true
}  

Let’s see the simple example of if statement in javascript.

Input:-
 <script>  
   let a = 20;
   if(a > 10){
      document.writeln("value a is greater than 10");  
   }
</script>

Output:-


If else statement

This conditional statement evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is given below:-

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

Let’s see the simple example of if else statement in javascript.

Input:-
 <script>  
   let a = 20;
   if(a%2 == 0){
      document.writeln("a is even number");  
   }  
   else{
      document.writeln("a is odd number");
   }
</script>

Output:-


If else if statement

This conditional statement evaluates the content only if expression is true from several expressions. The syntax of JavaScript if else if statement is given below:-

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  
}    

Let’s see the simple example of if else if statement in javascript:-

Input:-
 <script>  
	   let a = 20;
    if(a == 10){
       document.writeln("a is equal to 10");  
    }  
    else if(a == 15){
       document.writeln("a is equal to 15");
    }
    else{
       document.writeln("a is not equal to 10 or 15");
    }
</script>

Output:-