Submodule 7.3: Applying the "if" statements

The confirm interaction

confirm is a JavaScript method which displays a message box along with an OK and Cancel button. 

Confirm interaction

When the user clicks Ok JavaScript returns true whereas if it clicks Cancel it returns false.

Thus, this ready-made method gives us the capability to activate to different actions based on user's choice.  

In the below code the logic is: We have a variable which contains our confirm method. According to user's input, if this variable becomes true, do something, else do something else.

Notice that here we use the syntax if (likeBananas). This is equivalent with if (likeBananas==true)

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>The confirm interaction </title>
  </head>
  <body>
    <h3> The confirm interaction</h3>
    <script>
         var likeBananas;
         /*We're using confirm() to prompt the user for a boolean value*/
         likeBananas = confirm("Do you like bananas? ([OK] for yes, [Cancel] for no)");
         /*On next line we check the value and ... */
         if (likeBananas) {
                 /*on next line write some output if the value was true*/
                 document.write("You like Bananas!")
         } else {
                 /*on next line write some output if the value was false*/
                 document.write("You don't like babanas!")
         }
         /*The code outside the curly braces of the if else statement will always run.*/
         console.log ("Whether or not you had bananas, have a good day!");
    </script>
  </body>
</html>

Exercise

  1. Open your editor, create a new file and save it as exersice07.3.01.html in the folder "Exercises".
  2. Copy the above code and paste it in the new file.
  3. Save the file. Experiment by changing the values of the variables.