Project 371: Count to 21

4. (Demo) Use variables to keep track of data

To get the game working we're going to need both "if-else" statements to make decisions as well as a way to keep track of data. In this challenge, we're going to learn how to use variables to keep track of data. Think of a variable like a labeled box that stores information that you can pull up later. Once you have a good handle on how to work with variables, you'll be in good shape to start building the game. We're using a brand-new starting point here, so make sure to click the button below. 
Starting point link for this challenge

Steps

1. Open the JavaScript console

First, open up console by pressing  the "f12" key on your computer, or by right clicking on your browser window, clicking "Inspect" and clicking the "console" menu item. We'll start adding the code at the top of console window next to the blue ">"

2. Create a variable called "counter"

Type out "var counter = 0;" and hit enter. You'll see an "undefined" like in the image below because this command doesn't output any information, it just stores information.

This line of code is doing several things:

  1. "var" lets the browser know you're setting a new variable.
  2. "counter" is the name of the variable. You could have called it anything you want, as long as the spelling you use in your code is consistent.
  3. the "=" separates the name of the variable from what you want to set as it's value. The equals sign in code is very different from how you might have seen it in math class. It points to what goes into a variable, it doesn't check whether two values are equal.
  4. Whatever is on the right side of the "=" becomes what the variable stores. In this case, the variable stores the value 0
  5. The ";" tells the browser the statement is done
If you type out the name of the variable, "counter", you should see the value of the variable in the output.

3. Update the variable

You can rewrite the variable with a new number on the right side of the equals sign to update it. Try rewriting the line with a 1 instead of a 0.

Hint: You don't need to write the "var" again. You only need to do that the first time you create the variable.

Now when you type "counter" again, you should see 1 instead of 0.

4. Update the variable with itself

Anything to right of the "=" becomes the new value inside the variable. You might not have guessed it, but you can actually use the variable itself on the right side of the "=" with something like "counter = counter + 3;".

If the initial value of counter is 1, the "counter + 3" becomes 4. That's the new value of "counter", so the statement breaks down to something like:

  1. counter = counter + 3
  2. counter = 1 + 3
  3. counter = 4
So now, the new value of "counter" is 4

Try it out and see if you get the same result.