The else statement

Else is another conditional which is used after an if statement. 

What it actually says is " If something is true, go and do this, else do something else".

if (expression){
    //this code runs if expression evaluates to true
}else{
    //this code runs if expression evaluates to false
}
Example

The if else is generally used when we want to do only one test. For example, here we test only whether our entry is smaller than 5.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>The if else statement </title>
  </head>
  <body>
    <h3> The if else statement</h3>
    <script>
      var a = 5;
       var myNum;
       myNum = prompt("Write a number?");
       if (myNum < a) {
          document.write("You wrote the number " + myNum + ". This number is less than " + a +".")
       } else {
          document.write("You wrote the number " + myNum + ". This number is greater than " + a +".")
       }
    </script>
  </body>
</html>

Exercise

  1. Open your editor, create a new file and save it as exersice06.2.03ifelse.html in the folder "yourNameWEB2JS".
  2. Copy the above code and paste it into the new file.
  3. Save the file and preview it in your editor or your browser.
  4. Check your code by inserting the numbers 4,5,6 in the prompt window. What do you see?

Solution:

The only the case where the code doesn't work is if you have entered the number 5. We will improve it on the next page.