Syntax error What is if...else if... statement in JavaScript?

What is if...else if... statement in JavaScript?



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>
Updated on: 2020-06-13T11:41:16+05:30

409 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements