Part 05 / 09

Making Decisions

By the end of this part your game will judge every guess, answering Too high!, Too low! or Correct!, and will turn away guesses that make no sense.

7 sections 2 interactives
§ 5.1

Questions with yes-or-no answers

Every decision a program makes starts with a question that has only two possible answers. Is the guess bigger than the secret? Yes or no. Is it the same? Yes or no. In code, yes is true and no is false, and a question that gives one of them is a .

Your game needs three:

Comparison Asks With guess 70 and secret 42
guess > secret Is guess bigger than secret? true
guess < secret Is guess smaller than secret? false
guess === secret Are they exactly the same? false

Each row asks about the same two boxes, so with these values exactly one of the three is true. That’s always the case for two numbers: one is bigger, or smaller, or they’re the same. The game’s three answers come from this simple fact. The pointy end of > and < points at the smaller side, as in maths. The third one needs a closer look. A single = already has a job: in part 3 it meant “put into”, as in let secret = 42;. So asking “are these the same?” needs a different sign, and JavaScript’s is three equals signs in a row, ===. It is true only when both sides are the same value and the same kind of value. The number 42 and the string “42” are not the same, which is one more reason part 4’s Number() matters.

A comparison doesn’t change anything. It only produces an answer, true or false, which the next part of the code can act on. That answer is a value like any other, so you could even keep it in a box: after let tooHigh = guess > secret;, the box tooHigh holds true or false.

Two more comparisons are worth knowing. >= asks “bigger than or the same as?” and <= asks “smaller than or the same as?”. So 42 >= 42 is true, while 42 > 42 is false. You’ll need one of them in this part’s challenge.

Did you know?

JavaScript also has a double equals, ==, which converts values before comparing them, so “5” == 5 is true. The triple equals never converts: “5” === 5 is false. This series always uses ===, so a text guess can never quietly match a number.

§ 5.2

A fork in the road

A comparison gives an answer. To act on it, you use if:

if (guess === secret) {
message.textContent = "Correct!";
} else if (guess > secret) {
message.textContent = "Too high!";
} else {
message.textContent = "Too low!";
}

Picture the guess travelling down a road that splits three ways. At the fork stands a signpost with questions, read from the top. Is the guess equal to the secret? If so, take the first road. If not, is it bigger? If so, take the second. If neither, take the last road, the else, which has no question at all: it is where everything else goes.

The question in brackets after if is called the . When it’s true, the lines between the curly brackets run, and the browser skips every other road. When it’s false, it moves on to the next else if. Exactly one road is ever taken. Press Step through under the figure to send a guess of 70 down the road, one question at a time.

if (guess === secret)70 === 42 → falseelse if (guess > secret)70 > 42 → trueelseCorrect!Too high!Too low!guess = 70secret = 4270

Press Step through to send the guess down the road, one question at a time.

If, else if, else: the questions are asked from the top, and the first true one picks the road. The else road catches everything that's left.

The order of the questions matters. The browser stops at the first one that’s true, so if a guess could match two conditions, the higher one wins. In your game no guess can be both too high and correct, so this order is simply the clearest: the happy ending first, then the two hints.

§ 5.3

Build it: too high, too low

Step 1. Tell the number box which numbers make sense, with two settings in its tag:

game.html
<input id="guessInput" type="number" min="1" max="100">

Step 2. Rewrite the click listener. It now finds the message paragraph once and keeps it in a box, because it’s about to be used in three places, and then decides:

game.html
document.getElementById("guessButton").addEventListener("click", function () {
let input = document.getElementById("guessInput");
let message = document.getElementById("message");
let guess = Number(input.value);
if (guess === secret) {
message.textContent = "Correct!";
} else if (guess > secret) {
message.textContent = "Too high!";
} else {
message.textContent = "Too low!";
}
});

Step 3. Turn away guesses that make no sense, before the decision. Add these lines under the let guess line:

game.html
let guess = Number(input.value);
if (input.value === "" || Number.isNaN(guess) || guess < 1 || guess > 100) {
message.textContent = "Please type a number from 1 to 100.";
return;
}
if (guess === secret) {

The aside below explains each piece. The full file so far:

game.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Guess the Number</title>
</head>
<body>
<h1>Guess the Number</h1>
<p>I'm thinking of a number between 1 and 100.</p>
<input id="guessInput" type="number" min="1" max="100">
<button id="guessButton">Guess</button>
<p id="message"></p>
<script>
let secret = 42;
document.getElementById("guessButton").addEventListener("click", function () {
let input = document.getElementById("guessInput");
let message = document.getElementById("message");
let guess = Number(input.value);
if (input.value === "" || Number.isNaN(guess) || guess < 1 || guess > 100) {
message.textContent = "Please type a number from 1 to 100.";
return;
}
if (guess === secret) {
message.textContent = "Correct!";
} else if (guess > secret) {
message.textContent = "Too high!";
} else {
message.textContent = "Too low!";
}
});
</script>
</body>
</html>
§ 5.4 · interactive

Watch the decision

Before you test the game itself, step through the decision line by line. Choose a guess, then press Step and watch which lines run and which the browser jumps over.

Try it

Step through if, else if and else

Pick a guess: 30, 42 or 70. Each press of Step runs one line. The boxes on the right show the variables; the message shows what the page would say.

The guess
  1. let secret = 42;
  2. let guess = 70;
  3. if (guess === secret) {
  4. message.textContent = "Correct!";
  5. } else if (guess > secret) {
  6. message.textContent = "Too high!";
  7. } else {
  8. message.textContent = "Too low!";
  9. }
Boxes (variables)

No boxes yet.

Message on the page

6 steps

Press Step to run the first line.

Whichever guess you pick, exactly one of the three message lines runs.

Before each press, predict which line will light up next. Getting it right is the sign that you can read the code the way the browser does.

Try all three guesses. With 42 the very first question is true, and the browser never even asks whether 42 is bigger. With 30 both questions are false, and the else road catches it. Seeing the skipped lines is the whole point: the code that runs depends on the values in the boxes.

This is what makes a program more than a list. Up to now, every line of your script ran every time. From here on, the values in your boxes decide which lines run at all.

Reading code the way the stepper does, one line at a time, keeping track of what’s in every box, is one of the most useful skills in programming. When a program does something you didn’t expect, this is how you find out why: pretend to be the browser, with a pencil, and follow the lines. You’ll get faster at it with every part.

§ 5.5 · interactive

Check it works

Save, refresh, and play. The secret is still 42, so you know the answers in advance. That’s handy for testing: a good test is one where you know what should happen.

Try it

Your game at the end of part 5

The preview runs the full file above. Try 30, 50, 42, an empty box, 0 and 101.

game.html

Guess the Number

I'm thinking of a number between 1 and 100.

The secret is 42 in the preview too, until part 6 makes it random.

Testing a decision means testing every road, not just the one you hope the player takes. Here is a small test plan, the kind programmers write before they call something finished. Each row is one guess and the answer you should see:

Guess Road Answer
42 if Correct!
50 else if Too high!
30 else Too low!
1 and 100 else, else if Too low!, Too high!
empty, 0, 101 the guard Please type a number from 1 to 100.

The edges, 1 and 100, are worth testing on their own: mistakes like < instead of <= hide right at the edges.

What you should see

30 gives Too low!, 50 gives Too high! and 42 gives Correct!. An empty box, 0 or 101 all give Please type a number from 1 to 100.

§ 5.6

Break it on purpose

Change the first comparison from three equals signs to one, so it reads if (guess = secret) {. Save, refresh, and guess 30. The game says Correct!. Guess 99. Correct! again. Every guess wins.

The console is empty. The line is perfectly legal JavaScript; it just doesn’t say what you meant. A single = doesn’t ask a question, it puts a value into a box. So guess = secret takes the 42 out of secret and puts it into guess, throwing away the player’s guess. Then if looks at the result, 42, and treats it as a yes.

Why a yes? Because if doesn’t insist on true or false. It accepts any value and decides whether that counts as yes or no. Almost every value counts as yes: any number except 0, any text except the empty string. Only a handful count as no, such as false, 0, "" and NaN. 42 counts as yes, so the first road wins every time, and because guess now holds 42, it really does look correct.

This mistake is common enough that MDN’s reference for if has a section warning against it, and it’s why you’ll find yourself checking the equals signs in a condition out of habit. Remember the rule: one = puts, three === ask.

Put the other two equals signs back, save, refresh, and the game judges fairly again.

§ 5.7

Your challenge

Add a fourth answer: when a guess is wrong but within 3 of the secret, the game says “So close!” instead of “Too high!” or “Too low!”. With a secret of 42, that means any guess from 39 to 45 except 42 itself.

You’ll need a new else if with a condition that asks two things at once: is the guess at least 3 below the secret, and at most 3 above it? JavaScript’s “and” is &&, and it is true only when the questions on both sides are true. Where in the chain should your new road go?

When you test it, use the edges again: 39 and 45 should say “So close!”, and 38 and 46 shouldn’t. And 42 must still say Correct!.

Show a solution

It goes after the check for Correct!, so 42 still wins, and before the two hints:

game.html
if (guess === secret) {
message.textContent = "Correct!";
} else if (guess >= secret - 3 && guess <= secret + 3) {
message.textContent = "So close!";
} else if (guess > secret) {
message.textContent = "Too high!";
} else {
message.textContent = "Too low!";
}

>= means “bigger than or the same as”, and <= “smaller than or the same as”. If the road went above Correct!, a guess of exactly 42 would get “So close!”, because 42 is within 3 of itself. Notice that a close guess now loses its high or low hint; you could write “So close, but too high!” instead. Remove your new road before part 6.

The game judges guesses fairly, but its secret is always 42. In part 6 it learns to pick a number at random, and to count how many tries the player has had.

Sources for this part

Comparing

Deciding

History

Series Guess the Number: Your First Program
Menu

Gears & Signals · Static site · No trackers