JavaScript If..Else Statements


Conditional statements which are used to perform different actions based on different conditions.

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use if else to specify a block of code to be executed, if the same condition is false
  • Use if else if to specify a new condition to test, if the first condition is false

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax

if (condition) {
   // Statement(s) to be executed if condition is true  
}

Example

<script type="text/javascript">  
var a = 30;  
if(a > 20) {  
document.write("value of a is greater than 20");  
}  
</script> 
Output
 

The If..else Statement

Use the if...else statement to specify a block of code to be executed if the condition is false.

Syntax

if(condition){  
 //Statement(s) to be executed if condition is true
}  
else{  
 //Statement(s) to be executed if condition is false
}  

Example

<script type="text/javascript">  
var a=10;  
if(a%2==0){  
document.write("a is even number");  
}  
else{  
document.write("a is odd number");  
}  
</script> 
Output
 

The If...else if statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if(condition1){  
//Statement(s) to be executed if condition 1 is true 
}  
else if(condition2){  
//Statement(s) to be executed if condition 2 is true 
}  
else if(condition3){  
//Statement(s) to be executed if condition 3 is true  
}  
else{  
//Statement(s) to be executed if condition 3 is false  
}  

Example

<script type="text/javascript">  
var a = 10;  
if(a == 15) {  
document.write("a is equal to 15");  
}  
else if(a == 10) {  
document.write("a is equal to 10");  
}  
else if(a == 30) {  
document.write("a is equal to 30");  
}  
else{  
document.write("a is not equal to 15, 10 or 30");  
}  
</script> 
Output
 

Share this article on