Lesson Wednesday

Now that we've learned the basics of how to manipulate web pages with jQuery, we're going to add some logic to our pages that will allow us to control the flow of our code based on certain conditions. This kind of logic is called branching.

As an example, we are going to create a website for a bar. We only want to show the drinks menu to the user if they are over 21. So, the condition is age. When we come to determining this condition in the code, it is like a fork in the road with two paths or branches. If the user is over 21, they'll see the drinks menu. If not, they will get a message indicating that they are not old enough to view the content.

Here's an example:

drinks.html
<!DOCTYPE html>
<html>
  <head>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-1.10.2.js"></script>
    <script src="js/scripts.js"></script>
    <title>Drinks</title>
  </head>
  <body>
    <div class="container">
      <div id="drinks">
        <h1>Drink menu</h1>

        <h2>Beer</h2>
        <ul>
          <li>The King of Beer</li>
          <li>The Queen of Beer</li>
          <li>Real cold beer</li>
        </ul>

        <h2>Wine</h2>
        <ul>
          <li>Red wine</li>
          <li>White wine</li>
          <li>Blue wine</li>
        </ul>
      </div>

      <div id="under-21">
        <h1>Sorry, we can't serve you.</h1>

        <p>It's illegal in the US. Try Mexico or Europe.</p>
      </div>
    </div>
  </body>
</html>
css/styles.css
#drinks, #under-21 {
  display: none;
}
js/scripts.js
$(document).ready(function() {
  var age = parseInt(prompt("How old are you?"));

  if (age >= 21) {
    $('#drinks').show();
  }
});

A value entered into a prompt()field always returns a string even if a number is entered. Since we want our age to be compared to another number, we have to change it into a number using the parseInt() function.

Once we collect the user's age, we can write a JavaScript if statement, or a branch. If statements consist of the keyword if followed by a condition in parentheses. The condition will always evaluate to a boolean value: either true or false. After the condition, we add the code that we want to execute if the condition is true. This code is set between two curly braces on it's own lines. (Note the standards for an if statement: spacing, two-space indentation and NO semicolon after the final curly brace.)

When the condition evaluates to true, the code that follows between the curly braces is executed. If the condition is false, the code in the curly braces is not executed and the JavaScript processing moves on.

Let's work through a couple examples of our age condition. If our user indicates an age of 25, then the condition age >= 21 becomes 25 >= 21, which evaluates to true. The code in the curly braces is run and the div with an id of drinks is shown.

If age is 16, age >= 21 becomes 16 >= 21, which evaluates to false. In this case, the code in the curly braces is skipped and nothing is displayed.

Back to our code, let's show a different message if the condition is false (the user is under 21). To do this we'll add an else branch:

js/scripts.js
$(document).ready(function() {
  var age = parseInt(prompt("How old are you?"));

  if (age >= 21) {
    $('#drinks').show();
  } else {
    $('#under-21').show();
  }
});

Here, just like before, when the condition in parentheses evaluates to true, the code in the first set of curly braces is run. But when the condition evaluates to false, the code in the second set of curly braces, after the else keyword, is run.

An else statement does not need a condition because the code in its curly braces is what will be run when the if condition is false.

Generally, your code is executed from top to bottom, like a car driving straight down the road. When your car encounters an if statement, it is like encountering a fork in the road. You can't take both paths - if the condition is true, the if code runs, otherwise the else code runs.

What if we need to have more conditions? What if we want to display a special third message if the user is exactly 21? Let's pop up an alert that says "Now don't go crazy!" if the age is equal to (===) 21:

js/scripts.js
$(document).ready(function() {
  var age = parseInt(prompt("How old are you?"));

  if (age > 21) {
    $('#drinks').show();
  } else if (age === 21) {
    alert("Now don't go crazy!");
    $('#drinks').show();
  } else {
    $('#under-21').show();
  }
});

else if is just like an alternate if. It also has a condition to be checked in parenthesis next to it, and if that condition is true then the code in curly braces following it is run. But else if's condition is only checked when the if condition has already been found to be false.

In real life, you use this idea of if, else if and else all the time. Say you're going to the beach with your friends over the weekend. You all decide that the easiest way to get there would be to drive, but only your friend Lindsey has a car. So, if Lindsey is free, you can all drive with her. But, she never picks up her phone. So, you all decide that as an alternate plan you will take the bus - but only if Lindsey is busy. Then one of your friends remembers that this is a holiday weekend, so the bus might not be running. You roll your eyes at your friend and say "Fine, if we can't find Lindsey, and the buses aren't running, we can all just go to my house and watch movies." That is an if statement!

Let's re-interpret this discussion in pseudocode:

if (lindsey === "available to drive") {          // if Lindsey can drive...
  driveToBeach();                                // call the function to drive to the beach.
}
else if (busesAreRunning === true) {             // if Lindsey can't drive and the buses are running...
  busToBeach();                                  // take the bus to the beach.
}
else {                                           // if all the other options fail...
  watchMovies();                                 // watch movies instead.
}

The triple equals sign === is easy to mix up with the single equals sign =. Remember that the single equals sign (=) is used to assign a value to a variable. The triple equals (===) is used in conditions to check if the values on its left and right sides are equal.

When you are writing an if statement, you can have as many else if's in it as you like, but you can only have one if and one else. if must be the first statement, and else must be the last statement.

When JavaScript tries to figure out if the condition is true, it's looking for a boolean. You saw in the Assignment & Comparison Operators lesson that comparisons return a boolean - true or false. Check out what's going on here in the JavaScript console:

> var age = 22;
> age > 21;
true

We're getting a boolean. We could write the JavaScript for our drinks page like this:

js/scripts.js
$(document).ready(function() {
  var over21 = confirm("Are you over 21? Click OK for yes or Cancel for no.");

  if (over21) {
    $('#drinks').show();
  } else {
    $('#under-21').show();
  }
});

In other words, when I earlier said "If the condition in the parentheses is true, then the first statement is run," it's more precise to say "If the condition in the parentheses evaluates to true, then the first statement is run." (Note: this isn't 100% correct, as we'll see in the next lesson, but don't worry about that for now.)

Terminology


  • Branching: Determining the flow of your code based on certain conditions. (ie: If something is true, do one thing. If this same thing is false, do a different thing.)

  • Boolean: Returns true or false. When JavaScript is attempting to discern whether a condition is true, it's looking for a boolean.

  • Comparison operators: ===, >, <, >=, <=.

  • = sets a variable; === compares two things. Don't use ==.

Examples


One branch:

if (age > 21) {
  $('#drinks').show();
}

Two branches:

if (age > 21) {
  $('#drinks').show();
} else {
  $('#under-21').show();
}

Three branches:

if (age > 21) {
  $('#drinks').show();
} else if (age === 21) {
  $('#drinks').show();
} else {
  $('#under-21').show();
}

Branching can use a variable whose value is a boolean:

var over21 = true;
if (over21) {
  $('#drinks').show();
}

Comparison operators return booleans:

3 > 2;
// returns true