Part 04 / 09

Reading the Player's Guess

By the end of this part the player can type a number into your game, and the game will read it back to them, correctly, as a number.

6 sections 1 interactive
§ 4.1

A box for typing

A guessing game needs a guess. On a web page, the player types into an input element, a box drawn by the <input> tag:

<input id="guessInput" type="number">

It has an id like your other elements, guessInput, so the script can find it. It has no end tag, because nothing goes between: the player fills it in. And type="number" asks for a box made for numbers. The browser may give it small arrows for counting up and down, phones may show a number keypad, and it has a built-in check that rejects things that aren’t numbers.

Reading the box takes two steps. First find it, as you found the button:

let input = document.getElementById("guessInput");

A variable can hold more than numbers and text. This box, input, now holds the element itself, so you can use it by name instead of searching the page again. Second, ask the element what is typed in it:

input.value

.value is whatever is in the box right now. If the player typed 37, it is 37. Except, not quite.

Whatever the player types arrives as text. Even in a number box, .value is always a string. The player typed the characters 3 and 7, and that is what you get: "37", with quotes. It looks like a number. It isn’t one yet. And if the box is empty, or holds something that isn’t a valid number, .value is an empty string, "".

This isn’t a quirk of one browser: the HTML standard defines what is in a box as text, in every browser. Only your code knows the text is meant to be a number, so your code has to say so.

§ 4.2

When 5 + 5 makes 55

Remember from part 3 that + does two jobs: it adds numbers and glues strings. Now look at what happens when the guess is text:

"5" + 5

The browser sees a string on one side, so it turns the other side into text too, and glues: the answer is "55". Not 10. No error, no warning. It just quietly does the wrong job.

This catches almost everyone who learns JavaScript, because it’s invisible. “You guessed 5” looks the same whether the 5 is text or a number. The trouble only appears when you do arithmetic, or when you compare: is the guess bigger than the secret? With text, that question can give wrong answers.

Here’s how wrong. Compared as text, "10" > "9" is false. The browser compares text the way a dictionary sorts words, one character at a time, and the character 1 comes before 9, so “10” sorts first, just as “apple” comes before “banana”. As numbers, 10 is of course bigger. A guessing game that compared text would tell a player who typed 10, with a secret of 9, that they were too low.

The fix is to turn the text into a number before you use it. Number() does exactly that. Give it a string between its brackets and it gives back a number:

Number("37")

is the number 37, no quotes. Now Number("5") + 5 is 10, as you’d expect.

What if the text doesn’t look like a number? Number("hello") gives back a special value called NaN, short for “not a number”. And Number(""), an empty box, gives back 0. Both matter in part 5, when the game starts checking guesses.

Did you know?

An empty string turns into 0, not into “nothing”. That’s why, at the end of this part, clicking Guess with an empty box says “You guessed 0”.

§ 4.3

Build it: read the guess

Step 1. Add the number box just before the button, so they sit side by side:

game.html
<input id="guessInput" type="number">
<button id="guessButton">Guess</button>

Step 2. Change the click listener. It now finds the box, reads it, turns the text into a number and shows it:

game.html
document.getElementById("guessButton").addEventListener("click", function () {
let input = document.getElementById("guessInput");
let guess = Number(input.value);
document.getElementById("message").textContent = "You guessed " + guess;
});

Notice how the new lines lean on the boxes from part 3. Each line makes one box and fills it, and the next line uses that box by name. Programs are mostly built this way: small steps, each passing its result to the next.

Read the middle line from the inside out, the way the browser works it out: take input.value, the text in the box; hand it to Number(), which turns it into a number; put the result in a new box called guess.

Test after each step, not only at the end. After step 1 the box appears and you can type in it, but clicking still shows part 3’s whisper, because the listener hasn’t changed yet. That’s expected. If something does go wrong, you’ll know it was the step you just did.

The boxes input and guess are made inside the click listener, so they are made fresh on every click. That’s what you want: each click reads whatever is in the box at that moment. The line let secret = 42; stays where it is, at the top of the script. The game doesn’t use it in this part, but part 5 does.

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">
<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 guess = Number(input.value);
document.getElementById("message").textContent = "You guessed " + guess;
});
</script>
</body>
</html>
§ 4.4 · interactive

Check it works

Save, refresh, and try a few guesses in your page and in the preview. Edit, save, refresh, every time you change the file.

Try it

Your game at the end of part 4

The preview runs the full file above. Type a number and click Guess. Then try an empty box, a decimal and a negative number.

game.html

Guess the Number

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

The box in the preview is a real number box, so your browser treats letters the same way it does in your own file.

Try a few odd ones too. A negative number such as -5 comes back as You guessed -5. And type 1e3: the page says You guessed 1000. To a number box, the letter e is a way of writing powers of ten, so 1e3 means 1 followed by three zeros. It’s a valid number, so the box keeps it and Number() reads it, even though no player would ever type it on purpose. Odd inputs like these are worth trying in any program you write, because real users type things you never imagined.

What you should see

Type 37 and click Guess: the page says You guessed 37. Type 3.5 and it says You guessed 3.5. Clear the box and click: You guessed 0, because an empty box becomes 0. The game doesn’t yet care whether a guess makes sense; part 5 teaches it to.

§ 4.5

Break it on purpose

This time the mistake makes no error message at all, which is exactly why it’s worth seeing.

Take Number() away, so the line reads let guess = input.value;. Save, refresh, type 37 and click. The page still says You guessed 37. Gluing text into a sentence works perfectly well, so nothing looks wrong.

Now do a sum. Add one line under it that adds one to the guess:

game.html
let input = document.getElementById("guessInput");
let guess = input.value;
guess = guess + 1;
document.getElementById("message").textContent = "You guessed " + guess;

Type 37 again. The page says You guessed 371. The box guess held the text “37”, so + glued a 1 onto the end instead of adding. Open the console: it’s empty. As far as the browser is concerned, it did exactly what you asked.

This is the hardest kind of mistake: the program runs, and the answer is wrong. No line is broken, so there’s no line number to click. The only way to catch it is to check the result against what you expected, which is why every part of this series tells you exactly what you should see.

Notice that the line guess = guess + 1; is the counter pattern you’ll meet in part 6: take the value out of the box, add one, put it back. With a number in the box, it adds; with text, it glues.

Put Number() back, so the line is let guess = Number(input.value);, and type 37 once more. Now it says You guessed 38. Delete the extra line before you go on.

§ 4.6

Your challenge

Make the game do a sum with the guess. After “You guessed 37”, the page should add: “Your guess plus one is 38.”

There’s a trap waiting. The browser works through a line of + signs from left to right. Once it has glued a string, everything after it is glued too, even numbers. So "Your guess plus one is " + guess + 1 gives “…is 371”, even though guess is a real number. How can you make the adding happen first?

Try the trap first, on purpose, so you see it with your own eyes. Then think about part 3: a box can hold the result of a sum, and a box can be glued into a sentence.

Show a solution

Do the sum in its own box first, then glue the result into the sentence:

game.html
let input = document.getElementById("guessInput");
let guess = Number(input.value);
let plusOne = guess + 1;
document.getElementById("message").textContent = "You guessed " + guess + ". Your guess plus one is " + plusOne + ".";

Brackets work too: "…is " + (guess + 1) makes the browser add inside the brackets before it glues. Change the message back before part 5.

The game can read a guess. In part 5 it starts to judge it: too high, too low, or correct.

Sources for this part

The number box

Text and numbers

History

Series Guess the Number: Your First Program
Menu

Gears & Signals · Static site · No trackers