Understanding variables

See more about:

Where are we?

You know how to put JavaScript on a page, and show some messages. To go any further, you’ll need to know about variables.

This lesson’s goals

By the end of this lesson, you should know:

  • A variable is a place in computer memory to store data.
  • Variables let you keep data for later.
  • Variables make your code easier to write, and understand.
  • Variables help you accumulate data, like totals and counts.
  • The difference between global variables and local variables.

First thing – the word “variable” in computing does not mean the same thing it does in math.

Some people think you need to know a lot of math to write programs. They’re wrong. Wrong, wrong, WRONG! Many professional programmers don’t even know how to spell “calculus,” let alone do it.

A variable is a container. It’s a piece of computer memory that you put data into.

Variables have names, like total or last_name, so the computer can tell them apart. Here are two variables in memory:

total last_name
21 Smith

Variables can contain numbers or text.

CC
CC

OK, a variable is a little box with information in it. Right?

Kieran
Kieran

Yes, that’s a good way to think of it.

CC
CC

So… why would I care?

Kieran
Kieran

Using variables makes writing JavaScript easier. But it’s better to show you. Let’s look at how you use variables.

Variables save data until you need it

Sometimes you use variables to hold data you have now, that you’ll need later.

Like cake tins. Suppose you have two pies and a cake.

Two pies and a cake

You eat the two pies, and a slice of cake – yum! But now you’re full.

What do you do with the rest of the cake? Throw it away?

CC
CC

Are you crazy? Throw away cake? No! No! No! (Shakes paw)

Renata
Renata

I’d keep the cake. I’m going to want it later. Ahhh… cake!

Kieran
Kieran

Where do you put the cake?

Renata
Renata

Somewhere I can find it later, when I’m hungry.

You put the rest of the cake in a cake tin.

Saving the cake

When you’re hungry again, you take the cake out of the container, and nom, nom, nom.

A variable is like the cake tin. It’s a place for storing data. You put data into the variable, and take it out later, when you’re ready to use it.

Let’s write some code that uses variables in this way. You go to the store and buy some chew toys. Specifically, the new brain chew toy:

Brain

How much do you pay for the brains? It depends on (1) how many brains you buy, and (2) how much each one costs. Multiply the two together, and that’s the total you pay.

total = number of brains x price per brain

So if you buy 5 brains, and they’re $4 each, you pay $20.

Click the button, and you’ll run a program that makes the calculation.

When you click the button, the browser asks you for the number of toys you want to buy. You type that in, and click OK. Let’s say you type 5:

How many toys

Figure 1. How many toys?

The browser can’t use that 5 right away. It needs another piece of information – the price – before it can use the 5 to compute the total. We want to keep the 5 for later.

How? We tell the browser to store the 5 in a variable. When we’re ready to compute the total, the browser can get the 5 – or whatever you typed – from the variable.

Here’s the code:

var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);

Figure 2. Some code

Line 1 creates three variables, that is, three containers in the computer’s memory. Line 2 makes an input box:

How many toys

Figure 1 (again). How many toys?

Whatever the user types gets put into the variable number, for later use.

Line 3…

price = prompt('Price each?');

...shows another input box. It stores what the user enters in the variable price.

Line 4…

total = number * price;

...gets the contents of number, and the contents of price. It multiplies them together (* means multiply), and puts the result into another variable, total.

Some geeks call * “splat.”

Line 5…

alert('Total: $' + total);

...gets the contents of total, and shows it in an output box.

Let’s see that again, but this time we’ll see the values of the variables as they change. They start off empty.

number price total
     

Try a few different calculations.

So, we know that a variable is a container for data. One use for a variable is to save data for later, until it is ready to use. In the example we just saw, the program took the number of brains the user entered, and stored it in the variable number, until the program was ready to use that data to work out the total cost.

Exercise: Dance the seconds away

Joe loves to play Dance, Dance, Revolution. He spends hours at it. How many seconds is that?

Write a program that asks the user for the number of hours and minutes, and displays the number of seconds. Here’s an example of what happens when the program runs:

Hours

Minutes

Seconds

The formula is:

seconds = hours * 3600 + minutes * 60

Use this template. Add your own JavaScript:

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <title>Seconds</title>
  <script type="text/javascript">
    $(document).ready(function() {
      $("#compute_seconds").click(function(){
        Your code here.
      });
    });
  </script>
  <body>
    <p>
      <button type="button" id="compute_seconds">Compute</button>
    </p>
  </body>
</html>

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Variables make programming easier

Here’s the code again:

var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);

Figure 2 (again). Some code

We could write the code without variables:

alert('Total: $' + prompt('How many brain chew toys?') * prompt('Price each?'));

Figure 3. Evil code

Kieran
Kieran

Which do you prefer? With or without variables?

CC
CC

The second one is less typing.

Kieran
Kieran

That’s true.

Renata
Renata

But it’s hard to understand. When I read it, by the time I’m half way through, I’ve forgotten what happened at the start.

Kieran
Kieran

Good point!

CC
CC

Renata’s right. It’s easier to deal with things in small chunks, rather than combining everything into one complex mess.

CC said something important there. It’s easier on your brain to break off a small piece of a problem, and solve that, then another small piece, then another. Try to keep everything in your brain at once, and your head will explode.

Variables let you do things in small steps. Do a step, put the results in a variable. Do another step, results into another variable. Until you’re done.

This code…

var number, price, total;
number = prompt('How many brain chew toys?');
price = prompt('Price each?');
total = number * price;
alert('Total: $' + total);

Figure 2 (again). Some code

... breaks the task into small pieces. This code…

alert('Total: $' + prompt('How many brain chew toys?') * prompt('Price each?'));

Figure 3 (again). Evil code

... mixes everything up. As a beginner, write your code in small chunks. Your brain will thank you.

Variables can accumulate data

Variables are used to accumulate totals and counts. This is a variant of keep-data-for-later.

Suppose you work at a carnival. You run the ferris wheel.

Ferris wheel

People buy tokens to go on rides. Your ride costs one token. When someone climbs into your ferris wheel, they drop a token in a pot:

Ferris wheel pot

The number of tokens in the pot gets larger as the day goes on. A token for each new rider. The pot accumulates tokens.

A variable can be like that pot. The variables sits in memory, with a value in it:

ferris_count
12

A new rider comes along, and the value goes up:

ferris_count
13

Here’s a button you can click when a new person goes on the ride. Try it a few times.



Here’s the code:

<script type="text/javascript" >
$(document).ready(function(){
  var ferris_count = 0;
  $("#ferris_button").click(function(){
    ferris_count = ferris_count + 1;
    alert("Ferris wheel count: " + ferris_count);
  });
});
</script>
<p>
  <button type="button" id="ferris_button">Count</button>
</p>

Figure 4. The ferris pot

Line 3 creates a variable called ferris_count in the computer’s memory, and puts zero in it. This “initializes” the variable, giving it a starting value.

The line is outside the click function. This is important! Line 3 only runs once, when the page has been loaded. We only want to set ferris_count to zero once. More on that later.

When the button is clicked, lines 5 and 6 run. Here’s line 5:

ferris_count = ferris_count + 1;

This says “Get the value from ferris_count, add 1 to it, and put the result into ferris_count.” So, if ferris_count has 0 in it before line 5 is run, it would have 1 in it after line 5 has run. If it had 18 before, it will have 19 after. This is what we want: click the button, the variable goes up by one.

As it turns out, “add 1 to a variable” is common in programming. So there’s a shortcut in JavaScript:

ferris_count ++;

This does the same thing as ferris_count = ferris_count + 1;.

Line 6 shows the current value of the variable:

alert("Ferris wheel count: " + ferris_count);

You can watch the program as it runs. Click the Count button to get started. You can run the statements in the click() event one at a time, and watch what happens.

Scope

Here’s the ferris wheel code again:

<script type="text/javascript" >
$(document).ready(function(){
  var ferris_count = 0;
  $("#ferris_button").click(function(){
    ferris_count = ferris_count + 1;
    alert("Ferris wheel count: " + ferris_count);
  });
});
</script>
<p>
  <button type="button" id="ferris_button">Count</button>
</p>

Figure 4 (again). The ferris pot

Line 3 declares (creates) the variable:

var ferris_count = 0;

Something important: the variable is created outside the click function.

var ferris_count = 0;Variable created.
$("#ferris_button").click(function(){
    ferris_count = ferris_count + 1;Variable used.
    ..
});

Why? It has to do with something called “variable scope.” It’s a complex topic, but we don’t care about all the details. I’ll give you just two simple rules. Here’s the first one:

Use global variables when you want to count or total something. Declare the variables outside any function.

That’s what the ferris wheel example does. We want the browser to remember how many button clicks there were, so the next click adds one to that value. So:

var ferris_count = 0;Variable created.
$("#ferris_button").click(function(){
ferris_count = ferris_count + 1;Variable used.
..
});

ferris_count is declared outside the click() function. The memory for ferris_count is allocated when the page loads. It stays there, even when the user is not clicking on anything.

Suppose we mess it up:

<script type="text/javascript" >
$(document).ready(function(){
  $("#ferris_button").click(function(){
    var ferris_count;
    ferris_count = ferris_count + 1;
    alert("Ferris wheel count: " + ferris_count);
  });
});
</script>
<p>
  <button type="button" id="ferris_button">Count</button>
</p>

Figure 5. The ferris pot – brokeh

ferris_count is declared inside the click() function this time. (I left off the = 0 part (it used to be var ferris_count = 0), since that will just set it to zero each time.)

When the user clicks, line 4 will create the variable. Line 5 will add to it. Line 6 shows it. Line 7 ends the function, and destroys the variable!

That’s right. Variables declared inside a function are removed from memory when the function ends.

Click this button to run Figure 5:



What the…? The result varies between browsers. This is what I got in Firefox:

Brokeh output

Figure 6. Brokeh output

NaN means “not a number.” Let’s not worry about why the browser does that. The point is, it doesn’t work.

Variables declared outside any function are called “global variables.” They are created when the page loads, and vanish when another page loads.

Variables declared inside a function (like a click() function) are called “local variables.” They are created when the function starts, and vanish when the function ends. Each time the click() function runs, local variables are created and destroyed.

Remember the first scope rule:

Use global variables when you want to count or total something. Declare the variables outside any function.

Now let’s talk about the second scope rule.

Using the same variable in different functions

Suppose you quit the ferris wheel job. You get a new job at a local movie theater, counting ticket sales. Adults and children are counted separately.

Here are three buttons. One to count adult tickets, one to count child tickets, and the third to show how many of each type have been sold. Oh, and a fourth button to reset everything back to zero.

Play around with the buttons for a while.

 

Now let’s peek inside the code, and check out the variables in memory.

The page

 

Memory
adult child
0 0

Here’s the code:

<script type="text/javascript">
  $(document).ready(function() {
    var adult = 0;
    var child = 0;
    $("#sold_adult").click(function(){
      adult ++;
    });
    $("#sold_child").click(function(){
      child ++;
    });
    $("#show_sales").click(function(){
      alert("Adults: " + adult + "   Children: " + child);
    });
    $("#reset_tickets").click(function(){
      adult = 0;
      child = 0;
    });
  });
</script>
...
<button id="sold_adult" type="button">Sold adult ticket</button>
<button id="sold_child" type="button">Sold child ticket</button>
<button id="show_sales" type="button">Show sales</button>
...
<button id="reset_tickets" type="button">Reset</button>

Figure 7. The code

Lines 3 and 4 declare the two variables, adult and child. They are global variables, since both are declared outside any function. The variables are created in memory when the page loads, and removed when the page is unloaded.

Global variables are available to every function. For example, three separate click() functions use the variable adults.

Different functions can do different things to the same variable. The $("#sold_adult").click() function adds to adults. The $("#show_sales").click() function displays the value in adults. $("#reset_tickets").click() sets the variable back to zero.

This shows the second rule for variable scope:

Use global variables when you want to share data between functions.

Exercise: Count the goodies

Create a page that counts the donuts and muffins sold by a bakery. The page should look like this:

Page

The user clicks the buttons to record sales. The third button shows the sales so far. For example, suppose the user clicks the donut button four times, and the muffin button three times. The user clicks the Show Sales, and sees:

Sales

You can start with this code:

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Bakery sales</title>
    <script type="text/javascript">
      $(document).ready(function() {
      
        $("#sold_donut").click(function(){
          
        });
        $("#sold_muffin").click(function(){
          
        });
        $("#show_sales").click(function(){
          
        });
      });
    </script>
  </head>
  <body>
    <p>
      <button id="sold_donut" type="button">Sold a donut</button>
    </p>
    <p>
      <button id="sold_muffin" type="button">Sold a muffin</button>
    </p>
    <p>
      <button id="show_sales" type="button">Show sales</button>
    </p>
  </body>
</html>

Upload your solution to your server, and enter the URL below.

(Log in to enter your solution to this exercise.)

Summary

  • A variable is a place in computer memory to store data.
  • Variables let you keep data for later.
  • Variables make your code easier to write, and understand.
  • Variables help you accumulate data, like totals and counts.
  • Use global variables when you want to count or total something.
  • Use global variables when you want to share data between functions.

What now?

On this page, you saw code that runs when the user does something, like clicks on a button. Let’s talk about that button clicking.


How to...

Lessons

User login

Log in problems? Try here


Dogs