android-logo

JavaScript if else statement


Conditional statements are used to do various actions in response to certain conditions.

In JavaScript, there are three types of if statements.

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

if statement

The if statement is executed when a condition is true.


if (condition) {
    //  if the condition is true, a block of code will be performed
  }

Example


<script>  

var marks=86;
  
if(marks > 80 ){  
document.write("A Grade");  
}
  
</script>  

// Output - A Grade


if...else statement

The if statement is executed when a condition is true or else statement will be executed


if (condition) {
    //  if the condition is true
}else{
    //  if the condition is false
}

Example


<script>  

var marks=77;
  
if(marks > 80 ){  
document.write("A Grade");  
}else{
document.write("B Grade");  
}
  
</script> 

// Output - B Grade


It only analyzes the content if one or more expressions are true.


if (condition 1) {
    //  if the condition matches
}else if (condition 2){
    //  if the condition is matches
}else{
    //  if the condition is false
}

Example


<script>  

var marks=30;
  
if(marks > 80 ){  
document.write("A Grade");  
}
else if(marks > 40 ){  
document.write("B Grade");  
}
else{
document.write("Fail");  
}
  
</script>  

// Output - Fail


previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.