Writing Real Code: Going further - Head First JavaScript Programming (2014)

Head First JavaScript Programming (2014)

Chapter 2. Writing Real Code: Going further

image with no caption

You already know about variables, types, expressions... we could go on. The point is, you already know a few things about JavaScript. In fact, you know enough to write some real code. Some code that does something interesting, some code that someone would want to use. What you’re lacking is the real experience of writing code, and we’re going to remedy that right here and now. How? By jumping in head first and coding up a casual game, all written in JavaScript. Our goal is ambitious but we’re going to take it one step at a time. Come on, let’s get this started, and if you want to launch the next casual startup, we won’t stand in your way; the code is yours.

Let’s build a Battleship game

It’s you against the browser: the browser hides ships and your job is to seek them out and destroy them. Of course, unlike the real Battleship game, in this one you don’t place any ships of your own. Instead, your job is to sink the computer’s ships in the fewest number of guesses.

Goal: Sink the browser’s ships in the fewest number of guesses. You’re given a rating, based on how well you perform.

Setup: When the game program is launched, the computer places ships on a virtual grid. When that’s done, the game asks for your first guess.

How you play: The browser will prompt you to enter a guess and you’ll type in a grid location. In response to your guess, you’ll see a result of “Hit”, “Miss”, or “You sank my battleship!” When you sink all the ships, the game ends by displaying your rating.

image with no caption

Our first attempt...

For our first attempt we’re going to start simpler than the full-blown 7x7 graphical version with three ships. Instead we’re going to start with a nice 1-D grid with seven locations and one ship to find. It will be crude, but our focus is on designing the basic code for the game, not the look and feel (at least for now).

Don’t worry; by starting with a simplified version of the game, you get a big head start on building the full game later. This also gives us a nice chunk to bite off for your first real JavaScript program (not counting the Serious Business Application from Chapter 1, of course). So, we’ll build the simple version of the game in this chapter, and get to the deluxe version later in the book after you’ve learned a bit more about JavaScript.

image with no caption

First, a high-level design

We know we’ll need variables, and some numbers and strings, and if statements, and conditional tests, and loops... but where and how many? And how do we put it all together? To answer these questions, we need more information about what the game should do.

First, we need to figure out the general flow of the game. Here’s the basic idea:

1. User starts the game

a. Game places a battleship at a random location on the grid.

2. Game play begins

Repeat the following until the battleship is sunk:

a. Prompt user for a guess (“2”, “0”, etc.)

b. Check the user’s guess against the battleship to look for a hit, miss or sink.

3. Game finishes

Give the user a rating based on the number of guesses.

image with no caption

Now we have a high-level idea of the kinds of things the program needs to do. Next we’ll figure out a few more details for the steps.

A few more details...

We have a pretty good idea about how this game is going to work from the high-level design and professional looking flowchart, but let’s nail down just a few more of the details before we begin writing the code.

Representing the ships

For one thing, we can start by figuring out how to represent a ship in our grid. Keep in mind that the virtual grid is... well, virtual. In other words, it doesn’t exist anywhere in the program. As long as both the game and the user know that the battleship is hidden in three consecutive cells out of a possible seven (starting at zero), the row itself doesn’t have to be represented in code. You might be tempted to build something that holds all seven locations and then to try to place the ship in those locations. But, we don’t need to. We just need to know the cells where the ship is located, say, at cells 1, 2 and 3.

Getting user input

What about getting user input? We can do that with the prompt function. Whenever we need to get a new location from the user, we’ll use prompt to display a message and get the input, which is just a number between 0 and 6, from the user.

Displaying the results

What about output? For now, we’ll continue to use alert to show the output of the game. It’s a bit clunky, but it’ll work. (For the real game, later in the book, we’ll be updating the web page instead, but we’ve got a way to go before we get there.)

1. Game starts, and creates one battleship and gives it a location on three cells in the single row of seven cells.

The locations are just integers; for example, 1,2,3 are the cell locations in this picture:

image with no caption

2. Game play begins. Prompt user for a guess:

a. image with no caption

b. Check to see if user’s input hit any of the ship’s three cells. Keep track of how many hits there are in a variable.

3. Game finishes when all three cells have been hit and our number of hits variable value is 3. We tell the user how many guesses it took to sink the ship.

image with no caption

Sample game interaction

Working through the Pseudocode

We need an approach to planning and writing our code. We’re going to start by writing pseudocode. Pseudocode is halfway between real JavaScript code and a plain English description of the program, and as you’ll see, it will help us think through how the program is going to work without fully having to develop the real code.

In this pseudocode for Simple Battleship, we’ve included a section that describes the variables we’ll need, and a section describing the logic of the program. The variables will tell us what we need to keep track of in our code, and the logic describes what the code has to faithfully implement to create the game.

DECLARE three variables to hold the location of each cell of the ship. Let’s call them location1, location2 and location3.

DECLARE a variable to hold the user’s current guess. Let’s call it guess.

DECLARE a variable to hold the number of hits. We’ll call it hits and set it to 0.

NOTE

The variables we need.

DECLARE a variable to hold the number of guesses. We’ll call it guesses and set it to 0.

DECLARE a variable to keep track of whether the ship is sunk or not. Let’s call it isSunk and set it to false.

image with no caption

SHARPEN YOUR PENCIL

Let’s say our virtual grid looks like this:

image with no caption

And we’ve represented the ship locations using our location variables, like this:

location1 = 3;

location2 = 4;

location3 = 5;

Use the following sequence as your test user input:

1, 4, 2, 3, 5

Now, using the pseudocode on the previous page, walk through each step of code and see how this works given the user input. Put your notes below. We’ve begun the exercise for you below. If this is your first time walking through pseudocode, take your time and see how it all works.

NOTE

If you need a hint, take a quick peek at our answer at the end of the chapter.

image with no caption

Oh, before we go any further, don’t forget the HTML!

You’re not going to get very far without some HTML to link to your code. Go ahead and type the markup below into a new file named “battleship.html”. After you’ve done that we’ll get back to writing code.

image with no caption

image with no caption

BRAIN POWER

Flex those dendrites.

This is thinking ahead a bit, but what kind of code do you think it would take to generate a random location for the ship each time you load the page? What factors would you have to take into account in the code to correctly place a ship? Feel free to scribble some ideas here.

Writing the Simple Battleship code

We’re going to use the pseudocode as a blueprint for our real JavaScript code. First, let’s tackle all the variables we need. Take another look at our pseudocode to check out the variables we need:

image with no caption

Let’s get these variables into a JavaScript file. Create a new file named “battleship.js” and type in your variable declarations like this:

image with no caption

SERIOUS CODING

If you don’t provide an initial value for a variable, then JavaScript gives it a default value of undefined. Think of the value undefined as JavaScript’s way of saying “this variable hasn’t been given a value yet.” We’ll be talking more about undefined and some other strange values a little later.

Now let’s write the game logic

We’ve got the variables out of the way, so let’s dig into the actual pseudocode that implements the game. We’ll break this into a few pieces. The first thing you’re going to want to do is implement the loop: it needs to keep looping while the ship isn’t sunk. From there we’ll take care of getting the guess from the user and validating it—you know, making sure it really is a number between 0 and 6—and then we’ll write the logic to check for a hit on a ship and to see if the ship is sunk. Last, we’ll create a little report for the user with the number of guesses it took to sink the ship.

image with no caption

image with no caption

TO DO:

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

Step One: setting up the loop, getting some input

Now we’re going to begin to translate the logic of our game into actual JavaScript code. There isn’t a perfect mapping from pseudocode to JavaScript, so you’ll see a few adjustments here and there. The pseudocode gives us a good idea of what the code needs to do, and now we have to write the JavaScript code that can do the how.

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

Let’s start with all the code we have so far and then we’ll zero in on just the parts we’re adding (to save a few trees here and there, or electrons if you’re reading the digital version):

image with no caption

How prompt works

The browser provides a built-in function you can use to get input from the user, named prompt. The prompt function is a lot like the alert function you’ve already used—prompt causes a dialog to be displayed with a string that you provide, just like alert—but it also provides the user with a place to type a response. That response, in the form of a string, is then returned as a result of calling the function. Now, if the user cancels the dialog or doesn’t enter anything, then null is returned instead.

image with no caption

WATCH IT!

You might be tempted to try this code now...

...but don’t. If you do, your browser will start an infinite loop of asking you for a guess, and then asking you for a guess, and so on, without any means of stopping the loop (other than using your operating system to force the browser process to stop).

Checking the user’s guess

If you look at the pseudocode, to check the user’s guess we need to first make sure the user has entered a valid input. If so, then we also check to see if the guess was a hit or miss. We’ll also want to make sure we appropriately update the guesses and hits variables. Let’s get started by checking the validity of the user’s input, and if the input is valid, we’ll increment the guesses variable. After that we’ll write the code to see if the user has a hit or miss.

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

image with no caption

Let’s look a little more closely at the validity test. You know we’re checking to see that the guess is between zero and six, but how exactly does this conditional test that? Let’s break it down:

image with no caption

THERE ARE NO DUMB QUESTIONS

Q:

Q: I noticed there is a cancel button on the prompt dialog box. What gets returned from the prompt function if the user hits cancel?

A:

A: If you click cancel in the prompt dialog box then prompt returns the value null rather than a string. Remember that null means “no value”, which is appropriate in this case because you’ve cancelled without entering a value. We can use the fact that the value returned from prompt is null to check to see if the user clicked cancel, and if they did, then we could, say, end the game. We’re not doing that in our code, but keep this idea in the back of your mind as we might use it later in the book.

Q:

Q: You said that prompt always returns a string. So how can we compare a string value, like “0” or “6”, to numbers, like 0 and 6?

A:

A: In this situation, JavaScript tries to convert the string in guess to a number in order to do the comparisons, guess < 0 and guess > 6. As long as you enter only a number, like 4, JavaScript knows how to convert the string “4” to the number 4 when it needs to. We’ll come back to the topic of type conversion in more detail later.

Q:

Q: What happens if the user enters something that isn’t a number into the prompt? Like “six” or “quit”?

A:

A: In that case, JavaScript won’t be able to convert the string to a number for the comparison. So, you’d be comparing “six” to 6 or “quit” to 6, and that kind of comparison will return false, which will lead to a MISS. In a more robust version of battleship, we’ll check the user input more carefully and make sure they’ve entered a number first.

Q:

Q: With the OR operator, is it true if only one or the other is true, or can both be true?

A:

A: Yes, both can be true. The result of the OR operator (||) is true if either of the tests is true, or if both are true. If both are false, then the result is false.

Q:

Q: Is there an AND operator?

A:

A: Yes! The AND operator (&&) works similarly to OR, except that the result of AND is true only if both tests are true.

Q:

Q: What’s an infinite loop?

A:

A: Great question. An infinite loop is one of the many problems that plague programmers. Remember that a loop requires a conditional test, and the loop will continue as long as that conditional test is true. If your code never does anything to change things so that the conditional test is false at some point, the loop will continue forever. And ever. Until you kill your browser or reboot.

TWO-MINUTE GUIDE TO BOOLEAN OPERATORS

A boolean operator is used in a boolean expression, which results in a true or false value. There are two kinds of boolean operators: comparison operators and logical operators.

Comparison Operators

Comparison operators compare two values. Here are some common comparison operators:

<

means “less than”

>

means “greater than”

==

means “equal to”

===

means “exactly equal to” (we’ll come back to this one later!)

<=

means “less than or equal to”

>=

means “greater than or equal to”

!=

means “not equal to”

Logical Operators

Logical operators combine two boolean expressions to create one boolean result (true or false). Here are two logical operators:

||

means OR. Results in true if either of the two expressions is true.

&&

means AND. Results in true if both of the two expressions are true.

Another logical operator is NOT, which acts on one boolean expression (rather than two):

!

means NOT. Results in true if the expression is false.

So, do we have a hit?

This is where things get interesting—the user’s taken a guess at the ship’s location and we need to write the code to determine if that guess has hit the ship. More specifically, we need to see if the guess matches one of the locations of the ship. If it does, then we’ll increment the hits variable.

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

Here’s a first stab at writing the code for the hit detection; let’s step through it:

image with no caption

SHARPEN YOUR PENCIL

What do you think of this first attempt to write the code to detect when a ship is hit? Does it look more complex than it needs to be? Are we repeating code in a way that seems a bit, well, redundant? Could we simplify it? Using what you know of the || operator (that is, the boolean OR operator), can you simplify this code? Make sure you check your answer at the end of the chapter before moving on.

Adding the hit detection code

Let’s put everything together from the previous couple of pages:

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

image with no caption

Hey, you sank my battleship!

We’re almost there; we’ve almost got this game logic nailed down. Looking at the pseudocode again, what we need to do now is test to see if we have three hits. If we do, then we’ve sunk a battleship. And, if we’ve sunk a battleship then we need to set isSunk to true and also tell the user they’ve destroyed a ship. Let’s sketch out the code again before adding it in:

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

image with no caption

Provide some post-game analysis

After isSunk is set to true, the while loop is going to stop looping. That’s right, this program we’ve come to know so well is going to stop executing the body of the while loop, and before you know it the game’s going to be over. But, we still owe the user some stats on how they did. Here’s some code that does that:

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

image with no caption

Now let’s add this and the sunk ship detection into the rest of the code:

image with no caption

EXERCISE

Remember we said pseudocode often isn’t perfect? Well we actually left something out of our original pseudocode: we’re not telling the user if her guess is a HIT or a MISS. Can you insert these pieces of code in the proper place to correct this?

image with no caption

And that completes the logic!

Alright! We’ve now fully translated the pseudocode to actual JavaScript code. We even discovered something we left out of the pseudocode and we’ve got that accounted for too. Below you’ll find the code in its entirety. Make sure you have this typed in and saved in “battleship.js”:

Create loop and get user guess

Check user guess

Check if ship has been sunk

Display stats to user

var location1 = 3;

var location2 = 4;

var location3 = 5;

var guess;

var hits = 0;

var guesses = 0;

var isSunk = false;

while (isSunk == false) {

guess = prompt("Ready, aim, fire! (enter a number from 0-6):");

if (guess < 0 || guess > 6) {

alert("Please enter a valid cell number!");

} else {

guesses = guesses + 1;

if (guess == location1 || guess == location2 || guess == location3) {

alert("HIT!");

hits = hits + 1;

if (hits == 3) {

isSunk = true;

alert("You sank my battleship!");

}

} else {

alert("MISS");

}

}

}

var stats = "You took " + guesses + " guesses to sink the battleship, " +

"which means your shooting accuracy was " + (3/guesses);

alert(stats);

Doing a little Quality Assurance

QA, or quality assurance, is the process of testing software to find defects. So we’re going to do a little QA on this code. When you’re ready, load “battleship.html” in your browser and start playing. Try some different things. Is it working perfectly? Or did you find some issues? If so list them here. You can see our test run on this page too.

image with no caption

image with no caption

Boolean operators allow you to write more complex statements of logic. You’ve seen enough conditionals to know how to test, say, if the temperature is greater than 32 degrees. Or, that a variable that represents whether an item is inStock is true. But sometimes we need to test more. Sometimes we need to know not only if a value is greater than 32, but also if it’s less than 100. Or, if an item is inStock, and also onSale. Or that an item is on sale only on Tuesdays when the user is a VIP member. So, you see, these conditions can get complex.

Let’s step through a few to get a better idea of how they work.

Say we need to test that an item is inStock AND onSale. We could do that like this:

image with no caption

We can simplify this code by combining these two conditionals together. Unlike in Simple Battleship, where we tested if guess < 0 OR guess > 6, here we want to know if inStock is true AND onSale is true. Let’s see how to do that...

image with no caption

We don’t have to stop there; we can combine boolean operators in multiple ways:

image with no caption

SHARPEN YOUR PENCIL

We’ve got a whole bunch of boolean expressions that need evaluating below. Fill in the blanks, and then check your answers at the end of the chapter before you go on.

var temp = 81;

var willRain = true;

var humid = (temp > 80 && willRain == true);

What’s the value of humid? ________________________

var guess = 6;

var isValid = (guess >= 0 && guess <= 6);

What’s the value of isValid? ________________________

var kB = 1287;

var tooBig = (kB > 1000);

var urgent = true;

var sendFile =

(urgent == true || tooBig == false);

What’s the value of sendFile? ________________________

var keyPressed = "N";

var points = 142;

var level;

if (keyPressed == "Y" ||

(points > 100 && points < 200)) {

level = 2;

} else {

level = 1;

}

What’s the value of level? ________________________

EXERCISE

Bob and Bill, both from accounting, are working on a new price checker application for their company’s web site. They’ve both written if/else statements using boolean expressions. Both are sure they’ve written the correct code. Which accountant is right? Should these accountants even be writing code? Check your answer at the end of the chapter before you go on.

image with no caption

if (price < 200 || price > 600) {

alert("Price is too low or too high! Don't buy the gadget.");

} else {

alert("Price is right! Buy the gadget.");

}

image with no caption

if (price >= 200 || price <= 600) {

alert("Price is right! Buy the gadget.");

} else {

alert("Price is too low or too high! Don't buy the gadget.");

}

Can we talk about your verbosity...

image with no caption

We don’t know how to bring this up, but you’ve been a little verbose in specifying your conditionals. What do we mean? Take this condition for instance:

image with no caption

As it turns out, that’s a bit of overkill. The whole point of a conditional is that it evaluates to either true or false, but our boolean variable inStock already is one of those values. So, we don’t need to compare the variable to anything; it can just stand on its own. That is, we can just write this instead:

image with no caption

Now, while some might claim our original, verbose version was clearer in its intent, it’s more common to see the more succinct version in practice. And, you’ll find the less verbose version easier to read as well.

EXERCISE

We’ve got two statements below that use the onSale and inStock variables in conditionals to figure out the value of the variable buyIt. Work through each possible value of inStock and onSale for both statements. Which version is the biggest spender?

image with no caption

image with no caption

Finishing the Simple Battleship game

Yes, we still have one little matter to take care of because right now you’ve hard coded the location of the ship—no matter how many times you play the game, the ship is always at locations 3, 4 and 5. That actually works out well for testing, but we really need to randomly place the ship to make it a little more interesting to the user.

Let’s step back and think about the right way to place a ship on the 1-D grid of seven cells. We need a starting location that allows us to place three consecutive positions on the grid. That means we need a starting location from zero to four.

image with no caption

How to assign random locations

Now, once we have a starting location (between zero and four), we simply use it and the following two locations to hold the ship.

image with no caption

Okay, but how do we generate a random number? That’s where we turn to JavaScript and its built-in functions. More specifically, JavaScript comes with a bunch of built-in math-related functions, including a couple that can be used to generate random numbers. Now we’re going to get deeper into built-in functions, and functions in general a little later in the book. For now, we’re just going to make use of these functions to get our job done.

The world-famous recipe for generating a random number

image with no caption

We’re going to start with the Math.random function. By calling this function we’ll get back a random decimal number:

image with no caption

What we need is an integer between 0 and 4—that is, 0, 1, 2, 3 or 4—not a decimal number, like 0.34. To start, we could multiply the number returned by Math.random by 5 to get a little closer; here’s what we mean...

image with no caption

That’s closer! Now all we need to do is clip off the end of the number to give us an integer number. To do that we can use another built-in Math function, Math.floor:

image with no caption

THERE ARE NO DUMB QUESTIONS

Q:

Q: If we’re trying to generate a number between 0 and 4, why does the code have a 5 in it, as in Math.floor(Math.random() * 5)??

A:

A: Good question. First, Math.random generates a number between 0 and 1, but not including 1. The maximum number you can get from Math.random is 0.999.... When you multiply that number by 5, the highest number you’ll get is 4.999...

Math.floor always rounds a number down, so 1.2 becomes 1, but so does 1.9999. If we generate a number from 0 to 4.999... then everything will be rounded down to 0 to 4. This is not the only way to do it, and in other languages it’s often done differently, but this is how you’ll see it done in most JavaScript code.

Q:

Q: So if I wanted a random number between 0 and 100 (including 100), I’d write Math.floor(Math.random() * 101)?

A:

A: That’s right! Multiplying by 101, and using Math.floor to round down, ensures that your result will be at most 100.

Q:

Q: What are the parentheses for in Math.random()?

A:

A: We use parentheses whenever we “call” a function. Sometimes we need to hand a value to a function, like we do when we use alert to display a message, and sometimes we don’t, like when we use Math.random. But whenever you’re calling a function (whether it’s built-in or not), you’ll need to use parentheses. Don’t worry about this right now; we’ll get into all these details in the next chapter.

Q:

Q: I can’t get my battleship game to work. I’m not seeing anything in my web page except the “Play battleship” heading. How can I figure out what I did wrong?

A:

A: This is where using the console can come in handy. If you’ve made an error like forgetting a quote on a string, then JavaScript will typically complain about the syntax of your program not being right, and may even show you the line number where your error is. Sometimes errors are more subtle, however. For instance, if you mistakenly write isSunk = false instead of isSunk == false, you won’t see a JavaScript error, but your code won’t behave as you expect it to. For this kind of error, try using console.log to display the values of your variables at various points in your code to see if you can track down the error.

Back to do a little more QA

That’s all we need. Let’s put this code together (we’ve already done that below) and replace your existing location code with it. When you’re finished, give it a few test runs to see how fast you can sink the enemy.

image with no caption

Here’s one of our test sessions. The game’s a little more interesting now that we’ve got random locations for the ship. But we still managed to get a pretty good score...

image with no caption

EXERCISE

Wait a sec, we noticed something that looks wrong. Hint: when we enter 0, 1, 1, 1 things don’t look right! Can you figure out what’s happening?

image with no caption

It’s a cliff-hanger!

Will we find the bug?

Will we fix the bug?

Stay tuned for a much improved version of Battleship a little later in the book...

And in the meantime, see if you can come up with ideas for how you might fix the bug.

Congrats on your first true JavaScript program, and a short word about reusing code

You’ve probably noticed that we made use of a few built-in functions like alert, prompt, console.log and Math.random. With very little effort, these functions have given you the ability to pop up dialog boxes, log output to the console and generate random numbers, almost like magic. But, these built-in functions are just packaged up code that’s already been written for you, and as you can see their power is that you can use and reuse them just by making a call to them when you need them.

Now there’s a lot to learn about functions, how to call them, what kinds of values you can pass them, and so on, and we’re going to start getting into all that in the next chapter where you learn to create your own functions.

But before you get there you’ve got the bullet points to review, a crossword puzzle to complete... oh, and a good night’s sleep to let everything sink in.

image with no caption

BULLET POINTS

§ You can use a flowchart to outline the logic of a JavaScript program, showing decision points and actions.

§ Before you begin writing a program, it’s a good idea to sketch out what your program needs to do with pseudocode.

§ Pseudocode is an approximation of what your real code should do.

§ There are two kinds of boolean operators: comparison operators and logical operators. When used in an expression, boolean operators result in a true or false value.

§ Comparison operators compare two values and result in true or false. For example, we can use the boolean comparison operator < (“less than”) like this: 3 < 6. This expression results in true.

§ Logical operators combine two boolean values. For example true || false results in true; true && false results in false.

§ You can generate a random number between 0 and 1 (including 0, but not including 1) using the Math.random function.

§ The Math.floor function rounds down a decimal number to the nearest integer.

§ Make sure you use Math with an uppercase M, and not m, when using Math.random and Math.floor.

§ The JavaScript function prompt shows a dialog with message and a space for the user to enter a value.

§ In this chapter, we used prompt to get input from the user, and alert to display the results of the battleship game in the browser.

JAVASCRIPT CROSS

How does a crossword puzzle help you learn JavaScript? The mental twists and turns burn the JavaScript right into your brain!

image with no caption

Across

Down

3. To get input from a user, you can use the _________ function.

5. To randomly choose a position for a ship, use Math._________.

8. We keep track of whether a ship is sunk or not with a ________ variable.

9. If you don’t initialize a variable, the value is __________.

10. Boolean operators always result in true or _________.

11. Both while and if statements use __________ tests.

1. If you’re good at testing programs, you might want to become a ________ Assurance specialist.

2. == is a _____________ operator you can use to test to see if two values are the same.

3. This helps you think about how a program is going to work.

4. To get a true value from an AND operator (&&), both parts of the conditional must be ___________.

6. OR (||) and AND (&&) are ___________ operators.

7. JavaScript has many built-in __________ like alert and prompt.

10. To get a false value from an OR operator (||), both parts of the conditional must be __________.

SHARPEN YOUR PENCIL SOLUTION

Let’s say our virtual row looks like this:

image with no caption

And we’ve represented that by setting:

location1 = 3;

location2 = 4;

location3 = 5;

Assume the following user input:

1, 4, 2, 3, 5

Now, using the pseudocode on the previous page, trace through each step of code, and see how this works. Put your notes below. We’ve started the trace for you below. Here’s our solution.

location1

location2

location 3

guess

guesses

hits

isSunk

3

4

5

0

0

false

3

4

5

1

1

0

false

3

4

5

4

2

1

false

3

4

5

2

3

1

false

3

4

5

3

4

2

false

3

4

5

5

5

3

true

EXERCISE SOLUTION

We’ve got two statements below that use the onSale and inStock variables in conditionals to figure out the value of the variable buyIt. Work through each possible value of inStock and onSale for both statements. Which version is the biggest spender? The OR (||) operator!

image with no caption

image with no caption

SHARPEN YOUR PENCIL SOLUTION

We’ve got a whole bunch of boolean expressions that need evaluating below. Fill in the blanks. Here’s our solution:

var temp = 81;

var willRain = true;

var humid = (temp > 80 && willRain == true);

What’s the value of humid? true

var guess = 6;

var isValid = (guess >= 0 && guess <= 6);

What’s the value of isValid? true

var kB = 1287;

var tooBig = (kB > 1000);

var urgent = true;

var sendFile =

(urgent == true || tooBig == false);

What’s the value of sendFile? true

var keyPressed = "N";

var points = 142;

var level;

if (keyPressed == "Y" ||

(points > 100 && points < 200)) {

level = 2;

} else {

level = 1;

}

What’s the value of level? 2

EXERCISE SOLUTION

Bob and Bill, both from accounting, are working on a new price checker application for their company’s web site. They’ve both written if/else statements using boolean expressions. Both are sure they’ve written the correct code. Which accountant is right? Should these accountants even be writing code? Here’s our solution.

image with no caption

if (price < 200 || price > 600) {

alert("Price is too low or too high! Don't buy the gadget.");

} else {

alert("Price is right! Buy the gadget.");

}

image with no caption

if (price >= 200 || price <= 600) {

alert("Price is right! Buy the gadget.");

} else {

alert("Price is too low or too high! Don't buy the gadget.");

}

image with no caption

EXERCISE SOLUTION

Remember we said pseudocode often isn’t perfect? Well we actually left something out of our original pseudocode: we’re not telling the user if her guess is a HIT or a MISS. Can you insert these pieces of code in the proper place to correct this? Here’s our solution:

image with no caption

SHARPEN YOUR PENCIL SOLUTION

What do you think of this first attempt to write the code to detect when a ship is hit? Does it look more complex than it needs to be, or are we repeating code in a way that seems a bit, well, redundant? Could we simplify it? Using what you know of the || operator (that is, the boolean OR operator), can you simplify this code? Here’s our solution.

image with no caption

JAVASCRIPT CROSS SOLUTION

How does a crossword puzzle help you learn JavaScript? The mental twists and turns burn the JavaScript right into your brain! Here’s our solution.

image with no caption