Lesson Thursday

Note: In the video, there is the line return false; at the end of the submit action in the scripts.js file. This should be event.preventDefault(); with the parameter event passed into the function declaration.

Also, the text section includes a helpful trick for commonly-seen booleans.

Note: In the video, there is the line return false; at the end of the submit action in the scripts.js file. This should be event.preventDefault(); with the parameter event passed into the function declaration.

Also, the text section includes a helpful trick for commonly-seen booleans.

Sometimes, our branching logic can get more complicated. Let's build a website to give car insurance quotes. We'll keep it simple to start:

car-insurance.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>Car insurance</title>
  </head>
  <body>
    <div class="container">
      <h1>Car insurance</h1>

      <p>To give you a quote, we need to know a little about you:</p>

      <form id="insurance">
        <label for="age">Age</label>
        <input id="age" type="text">
        <label for="gender">Gender</label>
        <select id="gender">
          <option value="female">Female</option>
          <option value="male">Male</option>
        </select>

        <button type="submit" class="btn">Calculate my quote</button>
      </form>

      <div id="quote">
        <p>You will have to pay $<span id="rate"></span> per month to get car insurance. You should probably just bike or take the bus.</p>
      </div>
    </div>
  </body>
</html>
styles.css
.btn {
  display: block;
}

#quote {
  display: none;
}
scripts.js
$(document).ready(function() {
  $("form#insurance").submit(function(event) {
    var age = parseInt($("input#age").val());
    var gender = $("select#gender").val();

    var quote = (100 - age) * 3;

    $("#rate").empty().append(quote);
    $("#quote").show();

    event.preventDefault();
  });
});

Hopefully it's pretty clear how this works. Now, insurance companies generally charge more to men under 26. Let's add $50 to the quote for this demographic:

scripts.js
$(document).ready(function() {
  $("form#insurance").submit(function(event) {
    var age = parseInt($("input#age").val());
    var gender = $("select#gender").val();

    var quote = (100 - age) * 3;
    if (gender === 'male' && age < 26) {
      quote += 50;
    }

    $("#rate").text(quote);
    $("#quote").show()

    event.preventDefault();
  });
});

Here, we've used the && (and) operator. The expression gender === 'male' && age < 26 only evaluates to true if both conditions evaluate to true. You can try it out in the JavaScript console to see for yourself.

If we decide that we actually want to charge the premium to all men, and to anyone who's under 26, we can use the || (or) operator:

scripts.js
if (gender === 'male' || age < 26) {
  quote += 50;
}

The expression gender === 'male' || age < 26 evaluates to true if either condition evaluates to true.

One thing I don't like about our page is that it doesn't give an error if the user forgets to enter their age - it just treats it like their age is 0. Let's give an error if they leave the age field blank:

scripts.js
$(document).ready(function() {
  $("form#insurance").submit(function(event) {
    var age = parseInt($("input#age").val());
    var gender = $("select#gender").val();

    if (age) {
      var quote = (100 - age) * 3;
      if (gender === 'male' && age < 26) {
        quote += 50;
      }

      $("#rate").empty().append(quote);
      $("#quote").show();
    } else {
      alert('Please enter your age.');
    }

    event.preventDefault();
  });
});

Does this strike you as a little funny? Before now, all of the conditions for our if statements have evaluated to booleans. This time, we're looking at a string. If the user doesn't input a value, jQuery will return an empty string (with the car insurance page open, type $("input#age").val(); in the JavaScript console to see for yourself). An empty string isn't true or false.

What's happening here is that JavaScript has concepts called truthy and falsey. Falsey values include empty strings, the number 0, the number NaN, undefined, null (which we still haven't seen), and, of course, false itself. If JavaScript sees any of these as a branching condition, it will treat them as false. Everything else is truthy.

Here's another operator you should know about: if you want to test that something is not true, you can use the ! (not) operator like this:

if (!under18) {
  // do something only adults can do
}

Terminology


Logical operators:

  • && means and: gender === 'male' && age < 26
  • || means or: gender === 'male' || age < 26
  • ! means not: !under18

  • Empty strings, the number 0, the number NaN, undefined, null, and false itself are falsey. If JavaScript sees any of these as a branching condition, it will treat them as false. Everything else is truthy.