The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1){
Statement(s) to be executed if expression 1 is true
}
else if (expression2){
Statement(s) to be executed if expression 2 is true
}
else if (expression3){
Statement(s) to be executed if expression 3 is true
}
else{
Statement(s) to be executed if no expression is true
}Example
You can try to run the following to learn how to work with if…else if statement in JavaScript −
Live Demo
<html>
<body>
<script>
var book= "maths";
if( book== "history" ){
document.write("<b>History Book</b>");
}
else if(book == "maths" ){
document.write("<b>Maths Book</b>");
}
else if(book == "economics" ){
document.write("<b>EconomicsBook</b>");
}
else{
document.write("<b>Unknown Book</b>");
}
</script>
</body>
<html>