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 ?

<html>
   <body>
      <script>
         var book = "maths";
         if( book == "history" ){
            document.write("&lt;b&gt;History Book&lt;/b&gt;");
         }
         else if(book == "maths" ){
            document.write("&lt;b&gt;Maths Book&lt;/b&gt;");
         }
         else if(book == "economics" ){
            document.write("&lt;b&gt;Economics Book&lt;/b&gt;");
         }
         else{
            document.write("&lt;b&gt;Unknown Book&lt;/b&gt;");
         }
      </script>
   </body>
</html>
Updated on: 2020-06-13T11:41:16+05:30

459 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements