Chapter 14

Making Decisions with the If…Else Statement

When you need to make an either/or or yes/no decision, the if…else statement is your best friend. In this chapter, you learn how to use if…else statements to create and navigate choices in JavaScript programs.

image

Boolean Logic

In Chapter 9, we talk about JavaScript’s comparison operators and show you how they work in the JavaScript Super-Calculator. Let’s briefly review the comparison operators here.

Equality

The equality operators are == and ===. The difference between the two is that the double equals will convert values between different types. For example, if you compare 3 with "3", the == operator will say that they’re equal, while the triple equals operator will say that they aren’t.

The triple equals operator is called the strict equality operator. We recommend that you always use the strict equality operator in order to avoid bugs.

Not equal

The not equal operators are formed by putting an exclamation point (!) before the equality operators. They tell you whether two values are different. The strict not equal operator (!==) compares values without converting their type and the not equal operator (!=) converts between data types before comparing. We recommend that you always use the strict not equal operator.

Greater than and less than

The greater than (>) and less then (<) operators compare numeric values. Remember that the greater than and less than operators look like alligators, and the alligators want to eat the larger number. If the “mouth” of the alligator is open toward the larger number, the result will be true.

Greater than or equal and less than or equal

The greater than or equal and less than or equal operators work the same as the greater than or less than operators except that they also return true if the values are equal to each other.

The greater than or equal and less than or equal operators are formed by putting an equal sign to the right of the greater than or less than operators. For example:

3 >= 4 // returns false

4 >= 4 // returns true

4 >= 3 // returns true

3 <= 3 // returns true

3 <= 4 // returns true

4 <= 3 // returns false

Not greater than and not less than

Putting an exclamation point after the greater than or less than signs converts them into not greater than (>!) or not less than operators (<!).

warning If you’re like us, you may find not greater than and not less than operators to be confusing. Our advice: Don’t use the not operator with greater than and less than. In truth, not greater than does exactly the same thing as the simple less than, and not less than is precisely the same as greater than.

Table 14-1 shows all the comparison operators that you need to know and shows examples of each.

Table 14-1 All the Comparison Operators You Need

Operator

What It Does

True Example

===

Tests whether the value on the left is exactly equal to the one on the right.

14 === 14

!==

Tests whether the value on the left is not exactly equal to the one on the right.

14 !== 15

>

Tests whether the value on the left is greater than the one on the right.

15 > 14

<

Tests whether the value on the left is less than the one on the right.

14 < 15

>=

Tests whether the value on the left is either greater than or equal to the one on the right.

14 >= 14

<=

Tests whether the value on the left is either less than or equal to the one on the right.

14 <= 14

Introducing if…else Statements

Comparison operators aren’t really very useful by themselves. Most of the time, they’re used to make decisions inside of if…else statements.

The if…else statement looks like this:

if ([comparison]) {

  // statements to run if the comparison is true

} else {

  // statements to run if the comparison is false

}

technicalstuff The else part of the statement is optional. It’s perfectly valid and common to only have an if condition followed by the statement or statements that will run if the comparison is true.

Listing 14-1 shows an example of how you might use if…else in a program.

Listing 14-1 Using if…else

var language = prompt("What language do you speak?");

if (language === "JavaScript") {

  alert("Great! Let's talk JavaScript!");

} else {

  alert("I don't know what you're saying.");

}

To try out this program, follow these steps:

  1. Open JSFiddle in your web browser.
  2. Create a new blank program by clicking the JSFiddle logo.
  3. Type the code from Listing 14-1 into the JavaScript pane.
  4. Click Run or Update to execute the code.

    A pop-up window appears, asking you to input text.

  5. Type the word JavaScript (watch your capitalization!) into the pop-up and click OK.

    The first pop-up disappears and a second one opens that reads "Great! Let’s talk JavaScript!", as shown in Figure 14-1.

image

Figure 14-1: Using an if…else statement to choose between two paths.

Variables without operators

Sometimes, you may want to take a certain action only if a particular variable has a value or has been declared. To do this, you can just put the name of the variable in the parentheses after if. If the variable doesn’t exist or doesn’t have a value, it will result in a value of false.

Listing 14-2 expands the program from Listing 14-1 to create a variable called speaksJavaScript when you enter JavaScript into the prompt.

If you type in JavaScript correctly, the statement within the if block will execute, displaying a special message for JavaScript speakers only. If you enter anything other than JavaScript, the statement within the else block will execute, so that a different message will display.

Listing 14-2 Using Single-Word Operators

var language = prompt("What language do you speak?");

if (language === "JavaScript") {

  alert("Great! Let's talk JavaScript!");

  var speaksJavaScript = true;

} else {

  alert("I don't know what you're saying.");

}

if (speaksJavaScript) {

  alert("It's great to meet you.");

}

Combining Comparisons with Logical Operators

Logical operators allow you to combine more than one comparison operation. For example, let’s say you own a pizza parlor. Your policy is that if a customer’s order is more than $10 and they live within the city limits, they get free delivery.

In JavaScript, this rule requires two comparisons:

  • Is the order over $10?
  • Is the customer located within the city limits?

In order for the customer to get free delivery, both of these conditions have to be true. If one of these conditions is not true, the delivery charge is $5.

In JavaScript, you can specify that two conditions both need to be true by using the and operator (&&). To use the and operator in an if…else statement, you put it between two comparison expressions. Then you surround the whole combination expression with parentheses.

Listing 14-3 shows how you might write your pizza parlor’s delivery rule in JavaScript.

Listing 14-3 Pizza Parlor Free Delivery Rule in JavaScript

if ((deliveryCity === "Anytown") && (orderPrice > 10)) {

        var deliveryPrice = 0;

    } else {

        var deliveryPrice = 5;

    }

As a special deal, you might decide to offer free delivery to people when it’s their birthday, no matter how far away they live or the size of their order. In order to do this, you need to use the or operator (||). You type the or operator by holding down the Shift key and pressing the backslash () character on your keyboard twice.

Listing 14-4 shows how to write the new free delivery policy in JavaScript.

Listing 14-4 Free Delivery on Your Birthday

if (((deliveryCity === "Anytown") && (orderPrice > 10)) || (birthday === "yes")) {

        var deliveryPrice = 0;

    } else {

        var deliveryPrice = 5;

    }

In the next section, we start with this free delivery policy and create a program for managing several different parts of your pizza parlor.

Freshening Up the JavaScript Pizzeria

The JavaScript Pizzeria is a little mom-and-pop place in Anytown, USA. They pride themselves on making good pizzas at a good price and keeping things simple.

Currently, they have a web page where you can order one of their two kinds of pizza — cheese or pepperoni — and have it delivered to you for free if you live inside the city limits of Anytown, USA.

Customers are demanding more, though! They want additional pizza options. And people in other cities have been hearing about JavaScript Pizzeria, and they want pizza delivered, too! Some people have even asked for a special deal on their birthday!

As the JavaScript programmer for the JavaScript Pizzeria, it’s your job to whip up these new features so that the business continues to thrive! Don’t worry, we’re here to help.

Running the app

To test out the current version of the JavaScript Pizzeria website, follow these steps:

  1. Go to our public dashboard on JSFiddle at http://jsfiddle.net/user/forkids/fiddles.
  2. Find the program named “Chapter 14 – JavaScript Pizzeria – Start” and click its title to open it.
  3. Enter a number of pizzas, select a pizza type, and press the Place Order button.

    The total (at $10 per pizza) will display below the form.

That’s all there is to it! Move on to the next section to create your own version of the JavaScript Pizzeria that you can add new features to.

Forking the code (or just using your hands)

Follow these steps to create your own copy of the JavaScript Pizzeria program that you can add new features to:

  1. Open the program named “Chapter 14 – JavaScript Pizzeria – Start.”
  2. Click the Fork button in the top menu bar.
  3. Change the name of the program in the Fiddle Options on the left menu.
  4. Click Update to save your changes, and then click Set as Base.

Great! You’re ready to get started!

Planning the pizza parlor program improvements

Here are the three changes that we’ll make to the JavaScript Pizzeria program:

  • Add a new kind of pizza and charge extra for it.
  • Add new cities and calculate delivery charges for them.
  • Display the delivery charge.
  • Add a birthday special.

Each of these changes requires an if…else statement, as well as some small changes to the HTML.

Adding the new item to the menu

The most important new feature at this point is to spruce up the menu. The cook has invented a new kind of pizza that has bacon, arugula, apples, 14 different kinds of cheese, and a corn dog on top. He calls it the Supreme pizza.

The problem is, the Supreme pizza is very expensive to make — mostly because of that corn dog! It’s so difficult to find a gourmet corn dog in Anytown! So, the owner has decided to charge an extra $2 for each Supreme pizza.

Your job is to add the Supreme pizza to the menu and update the price when it gets ordered. Follow these steps to get started:

  1. Look in the HTML pane to find the place where the list of pizzas is created.

    It currently looks like this:

        <label>What kind of pizzas?

            <select id="typePizza">

             <option value="cheese">Cheese</option>

             <option value="pepperoni">Pepperoni</option>

            </select>

        </label>

  2. Add a new option element inside the select element to create the Supreme pizza option.

    It should have a value of "supreme", and the label (between <option> and </option>) should read Supreme.

  3. Click Update to save your work, and then test to make sure that Supreme shows up as a new option in the pizza type drop-down list, as shown in Figure 14-2.
  4. Find the calculatePrice() function.

    It looks like this:

    function calculatePrice(numPizzas, typePizza) {

        var orderPrice = Number(numPizzas) * 10;

        var extraCharge = 0;

        // calculate extraCharge, if there is one

        orderPrice += extraCharge;

        return orderPrice;

    }

  5. Right below the comment that reads calculate extraCharge, if there is one, type the following if…else statement:

        if (typePizza === "supreme") {

            extraCharge = Number(numPizzas) * 2;

        }

    This statement checks the typePizza variable to see if the Supreme was selected. If so, it will multiply the number of pizzas by two in order to get the number of dollars to add to the price.

  6. Save your work by clicking Update, and then try it out!

    If you select the Supreme pizza, you should now see that the total will be equal to $12 times the number of pizzas your ordered, as shown in Figure 14-3.

image

Figure 14-2: The new option has been added.

image

Figure 14-3: The new pie has been added!

Delivering to other cities

The pizzeria has to grow! But the population of Anytown can only eat so many pizzas, so management has decided to start delivery service to other, carefully chosen, cities.

There’s a catch, though! It’s not profitable to deliver just a single pizza or to deliver to Beverly Hills for free. We’ll need to charge $5 for delivery of orders less than or equal to $10 and for out-of-town delivery.

Follow these steps to put the new rules into place!

  1. In the HTML pane, locate the drop-down menu for the delivery city.

    It currently only has one option, Anytown.

  2. Add at least two more options to the drop-down.

    When it’s finished, it should look like this:

    <label>Where do you live?

      <select id="deliveryCity">

        <option value="Anytown">Anytown</option>

        <option value="Sacramento">Sacramento</option>

        <option value="Your Town">Your Town</option>

      </select>

    </label>

    You can replace Your Town with anything you like.

  3. Click Update to save your work and see your changes in the Result pane.
  4. In the JavaScript pane, find the calculateDelivery() function.

    It currently just sets everyone’s deliveryPrice to 0.

  5. Under the comment that reads calculate delivery price, if there is one, insert the following if…else statement.

    if ((deliveryCity === "Anytown") && (orderPrice > 10))

      {

        deliveryPrice = 0;

      } else {

        deliveryPrice = 5;

      }

  6. Save your work by clicking the Update button, and try out the form in the Result pane.

    If you select a city other than Anytown, or your order price is $10, a delivery fee of $5 will now be added to the total.

Displaying the delivery fee

Next, we need to display the delivery fee above the total, so that people know what they’re getting into.

To display the delivery fee, follow these steps:

  1. In the placeOrder() function, find the comment that reads todo: output the delivery price, if there is one.
  2. Below that comment, type the following if…else statements:

    if (deliveryPrice === 0) {

      theOutput += "<p>You get free delivery!</p>";

    } else {

      theOutput += "<p>Your delivery cost is: $" + deliveryPrice;

    }

    This if…else prints out a free delivery message if the deliveryPrice is 0. Otherwise, it prints out the delivery charge.

  3. Click Update to save your changes. Then try out the form in the Result pane.

    The new free delivery message is shown in Figure 14-4.

image

Figure 14-4: Telling the customer that they get free delivery is great for marketing!

Programming the birthday special

The final change that we’ll make to the program is to give people free delivery on their birthdays.

To program this change, follow these steps:

  1. In the HTML pane, add the birthday question to the form by typing this markup after the delivery city question:

    <label>Is it your birthday?

      <select id="birthday">

        <option value="yes">Yes</option>

        <option value="no">No</option>

      </select>

    </label>

  2. Click Update to save your work and to see your changes in the Result pane.

    If your Result pane doesn’t look like Figure 14-5, check your code carefully. You may also need to insert <br/> tags in order to put in the right amount of spacing between questions.

  3. Add the following to the placeOrder() function, below the other getElementById statements to get the value of the birthday form field:

    var birthday = document.getElementById("birthday").value;

  4. Add a third parameter to the calculateDelivery function definition for the birthday variable.

    function calculateDelivery(orderPrice, deliveryCity, birthday)

  5. Add an or operator and a new expression to the if…else statement in the calculateDelivery function to test whether the value of birthday is yes.

    if (((deliveryCity === "Anytown") && (orderPrice > 10)) || (birthday === "yes")) {

  6. Modify the statement in the placeOrder() function that calls calculateDelivery, to pass birthday as an argument:

    var deliveryPrice = calculateDelivery(orderPrice, deliveryCity, birthday);

  7. Click Update to save your work.
image

Figure 14-5: The Result pane with the new birthday question.

Listing 14-5 shows the completed JavaScript code for the JavaScript Pizzeria program.

Listing 14-5 The Completed JavaScript Pizzeria Program

// listen for button clicks

document.getElementById("placeOrder").addEventListener("click", placeOrder);

/**

* gets form values

* calculates prices

* produces output

*/

function placeOrder() {

    // get form values

    var numPizzas = document.getElementById("numPizzas").value;

    var typePizza = document.getElementById("typePizza").value;

    var deliveryCity = document.getElementById("deliveryCity").value;

    var birthday = document.getElementById("birthday").value;

    // get the pizza price

    var orderPrice = calculatePrice(numPizzas, typePizza);

    // get the delivery price

    var deliveryPrice = calculateDelivery(orderPrice, deliveryCity, birthday);

    // create the output

    var theOutput = "<p>Thank you for your order.</p>";

    // output the delivery price, if there is one

    if (deliveryPrice === 0) {

        theOutput += "<p>You get free delivery!</p>";

    } else {

        theOutput += "<p>Your delivery cost is: $" + deliveryPrice;

    }

    theOutput += "<p>Your total is: $" + (orderPrice + deliveryPrice);

    // display the output

    document.getElementById("displayTotal").innerHTML = theOutput;

}

/**

* calculates pizza price

*/

function calculatePrice(numPizzas, typePizza) {

    var orderPrice = Number(numPizzas) * 10;

    var extraCharge = 0;

    // calculate extraCharge, if there is one

    if (typePizza === "supreme") {

        extraCharge = Number(numPizzas) * 2;

    }

    orderPrice += extraCharge;

    return orderPrice;

}

/**

* calculates delivery price

*/

function calculateDelivery(orderPrice, deliveryCity, birthday) {

    var deliveryPrice = 0;

    // calculate delivery price, if there is one

    if (((deliveryCity === "Anytown") && (orderPrice > 10)) || (birthday === "yes")) {

        deliveryPrice = 0;

    } else {

        deliveryPrice = 5;

    }

    return deliveryPrice;

}

Listing 14-6 shows the completed HTML markup for the JavaScript Pizzeria.

Listing 14-6 The Final HTML

<h1>JavaScript Pizzeria</h1>

<div id="orderForm">

    <label>How many pizzas do you want?

        <input type="number" id="numPizzas" />

    </label>

    <br />

    <br />

    <label>What kind of pizzas?

        <select id="typePizza">

         <option value="cheese">Cheese</option>

         <option value="pepperoni">Pepperoni</option>

         <option value="supreme">Supreme</option>

        </select>

    </label>

    <br />

    <br />

    <label>Where do you live?

        <select id="deliveryCity">

         <option value="Anytown">Anytown</option>

         <option value="Sacramento">Sacramento</option>

         <option value="Beverly Hills">Beverly Hills</option>

        </select>

    </label>

    <br />

    <br />

    <label>Is it your birthday?

        <select id="birthday">

         <option value="yes">Yes</option>

         <option value="no">No</option>

        </select>

    </label>

    <br />

    <br />

    <button type="button" id="placeOrder">Place Order</button>

</div>

<div id="displayTotal"></div>

Figure 14-6 shows the final program’s Result pane after placing our lunch order today.

image

Figure 14-6: Our lunch order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset