Part 03 / 09

Output and Variables

By the end of this part your game will invite the player to guess, and will keep its secret number in a labelled box called a variable.

6 sections 1 interactive
§ 3.1

Labelled boxes

A guessing game has to remember things: the secret number, how many guesses are left, what the player said last. Programs remember things in .

Picture a variable as a box with a label on it. The label is the variable’s name, and inside the box is its , one piece of information such as the number 42. You make a box like this:

let secret = 42;

Read it as: let there be a box called secret, and put 42 in it. The word let makes the new box. The name comes next. The = sign doesn’t mean “equals” here, as it would in maths. It means “put into”: take the value on the right and put it in the box on the left.

Once the box exists, you use it by its name. Wherever your code says secret, the browser looks in the box and uses whatever is there. You can also put something new in the box, without let this time, because the box already exists:

secret = 7;

A box holds one value at a time. The 7 goes in and the 42 is gone. Nothing keeps a copy of the old value unless you put it in a box of its own.

Use let once per box. It makes the box; a plain = refills it. If you write let secret a second time, the browser refuses the whole script with the error “Identifier ‘secret’ has already been declared”: there is already a box with that label.

Names follow a few rules: no spaces, and no starting with a digit. This series writes names the way most JavaScript programmers do, joining words and giving each new word a capital, as in guessButton. Pick names that say what is in the box. Six months from now, secret will mean something to you; x won’t.

§ 3.2

Text and numbers

Not every value is a number. Your page is full of text: “Guess the Number”, “You clicked!”. In code, a piece of text is called a , as in a string of letters, and it always goes between quotes:

let name = "Alex";

The quotes must match: a string that starts with " ends with ". JavaScript also accepts single quotes, 'Alex', but this series uses double quotes throughout, so you never have to wonder which.

A goes without quotes: 42, 7, 3.5. The quotes are how the browser tells the two apart, and the difference matters, because they behave differently. You can do sums with numbers. With strings you can do something else: join them together.

The + sign does both jobs. Between two numbers it adds them, so 40 + 2 is 42. Between two strings it glues them end to end, so "Good " + "luck" is “Good luck”. Notice the space inside the quotes after Good. The browser joins exactly what you give it and adds nothing, so without that space you’d get “Goodluck”.

When one side is a string and the other a number, the browser turns the number into text and glues them:

"My number is " + 42

gives “My number is 42”. That is how a program puts a value from a box into a sentence, and how your game will soon say things like “You found it in 5 tries”.

So 42 and "42" look alike but aren’t the same thing: one is a number you can add to, the other is two characters of text. Keep that in mind. In part 4 it causes a surprise that catches almost every beginner, and you’ll meet it head on.

§ 3.3

Build it: a secret number

Your game gets an invitation to play and a secret number. The number is fixed at 42 for now; in part 6 the computer will pick it at random.

Step 1. Add a paragraph under the heading that tells the player what’s going on:

game.html
<h1>Guess the Number</h1>
<p>I'm thinking of a number between 1 and 100.</p>

This sentence never changes, so it belongs in the HTML. The script only handles text that changes.

Step 2. At the top of the script, make the box for the secret:

game.html
<script>
let secret = 42;
document.getElementById("guessButton").addEventListener("click", function () {

Step 3. Change what the click does. Instead of “You clicked!”, the game will whisper its secret, so you can see the box really holds 42:

game.html
document.getElementById("guessButton").addEventListener("click", function () {
document.getElementById("message").textContent = "Psst! My number is " + secret + ".";
});

Three pieces are glued together here: the string “Psst! My number is “, the value in the box secret, and a string holding a single full stop. Giving away the secret is only for now. In part 5 the game will keep it and answer “Too high!” or “Too low!” instead.

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>
<button id="guessButton">Guess</button>
<p id="message"></p>
<script>
let secret = 42;
document.getElementById("guessButton").addEventListener("click", function () {
document.getElementById("message").textContent = "Psst! My number is " + secret + ".";
});
</script>
</body>
</html>
§ 3.4 · interactive

Check it works

Save, then refresh. Under the heading you should see the invitation. Click Guess and the game gives itself away. Compare yours with the preview:

Try it

Your game at the end of part 3

The preview runs the full file above. Click Guess.

game.html

Guess the Number

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

In the preview, as in your file, the secret is always 42 for now.

Now refresh the page and click again. The secret is still 42, because refreshing runs the script again from the top, and the first thing it does is make the box secret and put 42 in it. Variables only last while the page is open. Close the tab and every box is gone; open the file again and they are made afresh. A game that remembers something after the page closes needs more than a variable, and one of the extra challenges in part 9 shows how.

What you should see

Under the heading it says I’m thinking of a number between 1 and 100. When you click Guess, the words Psst! My number is 42. appear under the button.

§ 3.5

Break it on purpose

What happens if the code uses a box that was never made? Delete the line let secret = 42;, save, refresh and click Guess. Nothing appears, and the console has a new red message:

Uncaught ReferenceError: secret is not defined game.html:18

A ReferenceError means the code referred to a name the browser has never heard of. There is no box called secret, so there is nothing to look inside. The line number points at the line that tried to use it. (If you deleted the line entirely, everything below moved up one, which is why it says 18.)

Notice when the error appeared: not when the page loaded, but when you clicked. Until then the browser had no reason to look for secret, because the code that uses it only runs on a click. An error appears when the broken line runs, not before.

You’ll get a similar message if a box is used before the line that makes it has run, for example if you moved let secret = 42; below a line that uses secret straight away. Chrome then says “Cannot access ‘secret’ before initialization”: the box is spoken for, but nothing has been put in it yet. Order matters, just like on the recipe card.

Every programmer meets “is not defined” constantly, usually because of a spelling slip: secrte instead of secret. When you see it, look for a typo first. Put the line back, save and refresh, and the game whispers its secret again.

§ 3.6

Your challenge

Make the game greet the player by name when the page opens, before anyone clicks: “Good luck, Alex!”

You’ll need a second box, holding the player’s name as a string, and a line that joins it into the greeting and shows it in the message paragraph. Where in the script should that line go, so that it runs when the page loads rather than on a click?

Here’s a hint. Everything inside the click listener’s curly brackets waits for a click. Everything outside them runs at once, from top to bottom, as the page loads. And watch the spaces and the exclamation mark: they have to be inside the quotes too.

Show a solution

Put both lines under let secret = 42;, outside the click listener, so they run as soon as the browser reads them:

game.html
let secret = 42;
let playerName = "Alex";
document.getElementById("message").textContent = "Good luck, " + playerName + "!";

When you click Guess, the click listener replaces the greeting with the secret, because a paragraph shows one text at a time, just like a box. Remove these two lines before part 4 to match the series.

The game has a secret, but the player still can’t guess. In part 4 you add a box to type in, and discover that whatever the player types arrives as text.

Sources for this part

Variables and values

Showing text safely

Errors

History

Series Guess the Number: Your First Program
Menu

Gears & Signals · Static site · No trackers