Variables: labelled boxes for changing information — Computing, 7–10 years
A variable gives a changing piece of information a name. This lets a program remember a score, a name or a temperature and use the latest value instead of treating every case as completely new.
A named place for a value
Think of a variable as a labelled box in the computer’s working memory. The label might be score, and the box might contain 12; later, it can contain 13. The program uses the label to find the current value, so it does not need to remember a separate instruction for every possible score.
Why do programs need memory?
A program often has to use information again after something has happened. A game needs to know the score after a player moves; a form needs to remember a name after it is typed. Variables solve the problem of keeping these changing facts in one place that instructions can refer to.
Keeping a game score
Start with the variable score set to 0. The player catches a star, so the program changes score to 0 + 1, which is 1. The player catches two more stars, so it adds 1 twice: 2, then 3. When the screen displays score, it shows 3 because that is the value in the box now.
The label is not the value
It is easy to mix up a variable’s name with what it contains, because we use both words together. If score contains 7, score is not another word for 7: it is the label that points to 7. When the player earns a point, the value changes, but the label score can stay the same.
Scores, shopping baskets and sensors
A game stores your score, an online basket stores how many items you chose, and a weather station stores the latest temperature. In each case, the value can change while the useful name stays familiar. Variables make it possible to update the information without rebuilding the whole program.
Keep exploring
Other languages
Loading MyLeoNes™…