Google News
logo
Javascript If Else
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are following three statements in JavaScript.

1. If Statement
2. If else statement
3. if else if statement
If statement
Use if conditional statement if you want to execute something based on some condition.
Syntax :

if(condition expression)
{
   // code to be executed if condition is true
}
Example :
<html>
<head>
<title>If Statement</title>
</head>
 
<body>
 
<script type="text/javascript">  

  var A=20;  
  if(A>10){  
  document.write(" A is greater than 10");  
  } 
 
</script>  
 
</body>
</html>
Output :

A is greater than 10

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

if(expression){
  //The code will be executed if condition is true
}
else{
  //The code will be executed if condition is false
}
Example :
<html>
<head>
<title>If else Statement</title>
</head>
 
<body>
 
<script type="text/javascript">  

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

A is even number

If...else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax :

if(condition1){
  //code will be executed if condition1 is true
}
else if(condition2){
  //code will be executed if condition1 is false and condition2 is true
}
else{
  //code will be executed if condition1 is false and condition2 is false
}
Example :
<html>
<head>
<title>If else if Statement</title>
</head>
 
<body>
 
<script type="text/javascript"> 
 
var a=20;  
if(a==10){  
document.write("A is equal to 10");  
}  
else if(a==20){  
document.write("A is equal to 20");  
}  
else{  
document.write("A is not equal to 10, 20");  
}  

</script>  
 
</body>
</html>
Output :

A is equal to 20