Bright Java Tutorial

is brought to you by DoITBright LLC

Javascript

If, Else If and Else Statement

When writing programs, it is very common that we will need to control the flow of execution based on a certain logic. Let us think of simple example for now, a test for equality. Lets say, we want to compare if the two given numbers are equal. The result of the check will either be equal to true or false. If it is true, we wish to perform a set of instructions. If it is false, we might wish to perform a different set of instructions. Lets take a look at the example below.

  <html>
    <head>
      <title>If, Else If and Else In Javascript.</title>
    </head>
    <body>
       <script type="text/javascript">
         var itemPrice = 1;
         if(itemPrice == 1) {
           document.write("Item price is 1 dollar.");
         } else {
           document.write("Item price is not 1 dollar.");
         }
       </script>
    </body>
  </html>
                           

In the Javascript code example above, we declared a variable and name it as itemPrice. We initialized it to a value of 1. After that, we tested the itemPrice variable for equality. Is itemPrice equal to one? If yes, print 'Item price is 1 dollar.'. If not, print 'Item price is not 1 dollar.'. As you may have guessed, the code inside the if statement will get executed since the test for equality is satisfied. The 'else' condition is skipped. How about this kind of scenario?

  <html>
    <head>
      <title>If, Else If and Else In Javascript.</title>
    </head>
    <body>
       <script type="text/javascript">
         var itemPrice = 2;
         if(itemPrice == 1) {
           document.write("Item price is 1 dollar.");
         } else if(itemPrice == 2) {
           document.write("Item price is 2 dollars.");
         } else {
           document.write("Item price is not 1 dollar.");
         }
       </script>
    </body>
  </html>
                           

In the code above, we introduced the 'else if' block of code. Let us interpret how the code works. We initialized a variable and named it as itemPrice with an initial value of 2. Then, we tested if the variable has a value equal to 1. The condition is not satisfied since itemPrice has a value of 2. Then, it will test the 'else if' condition. Is itemPrice has a value equal to 2? The condition is satisfied. It will execute the code inside the 'else if' block of code. The 'else' condition will be skipped since the 'else if' was already satisfied.


Back    Next