Find a course

Module 2: Building Blocks of CodeLesson 5 of 79 min

Variables: Boxes That Remember

How does a game remember your score? Learn what variables are, how to change their values, and write code that adds points to a score.

Step 1 of 12Learn

A box with a label

In a game, your score goes up when you grab a coin. How does the computer remember it? It uses a variable.

Think of a variable as a box with a label. The label is the name, like score. Inside the box is the value, like 0.

let score = 0;

This line makes a box called score and puts 0 inside. The word let means "make a new variable."

A variable is a box with a label: the label "score" is the name and the 0 inside is the valuescore0value insidename (label)let score = 0;

Step 2 of 12Practice · Fill in the blanks

Fill in the blanks

In let lives = 3; the variable's name is and its value is .

Word bank

Step 3 of 12Learn

Changing the value

Variables can change. That is why they are called variables: their values vary.

score = score + 10;

This looks strange at first. Read it right to left: take what is in score, add 10, and put the new number back into score.

If score was 0, it is now 10. Run the line again and it becomes 20. The = sign here does not mean "equals" like in math. It means "store this value."

Step 4 of 12Diagram

A variable changes

A variable changesProcess diagram: score 0 → + 10 → score 10 → + 10 → score 20.score 0+ 10score 10+ 10score 20
score 0
+ 10
score 10
+ 10
score 20

Step 5 of 12Practice · Work it out

score starts at 5. Then the code runs score = score + 10 two times. What is score now?

Step 6 of 12Practice · Code challenge

Finish addPoints(score) so it returns the score plus 10 points.

Runs in a sandbox in your browser.
  • addPoints(0)
  • addPoints(25)
  • addPoints(90)

Step 7 of 12Note

Step 8 of 12Compare

Good names vs. confusing names

AspectGood nameConfusing name
Your scorescorex
Lives leftlivesthing
Player's nameplayerNameplayer name (spaces are not allowed)

Step 9 of 12Practice · Select all that apply

Which would make good variable names in a game? Pick all that are right.

Select all that apply.

Step 10 of 12Practice · Choose one

Variables can hold different kinds of values. Which one is a string (text)?

Step 11 of 12Practice · Put in order

Put these lines in order so the game starts with 3 lives and loses one when the player is hit.

Drag the items, or use the arrow buttons, to put them in order.

  1. player gets hit
  2. lives = lives - 1;
  3. show lives on screen
  4. let lives = 3;

Step 12 of 12Practice · True or false

In code, score = score + 1 means the same as a math equation that can never be true.