Variables and program state — Computing, 14–17 years
A program needs a way to remember values, change them and use the latest value later. Variables make that changing memory visible.
What a variable does
A variable is a named place for a value that a program may need again. The value can be a number, text or true/false, and it can change while the program runs. At any moment, the variable represents the value stored there now.
Why programs need state
Without stored values, a program would forget almost everything between instructions. Early programmers needed machines to keep counts, measurements and settings while a calculation was under way. Variables solve this problem by giving changing information a name, so later instructions can read it or replace it.
A changing score
Start with score = 12. A player earns 5 points, so the program performs score = score + 5: it reads 12, adds 5 and stores 17 back in score. Then a penalty of 3 gives score = score - 3, leaving 14. The name stays the same; its value changes.
The right side is read first
A common mistake is reading score = score + 5 as if ordinary algebra allowed it, because the same name appears twice. In programming, the right side is calculated first using the old value, and only then is the result stored on the left. This feels odd because the symbol = means assignment here, not a claim that both sides already match.
Where state appears
A shopping basket remembers its items, a music app remembers the current position, and a game remembers health or points. These are all program state: information that changes as someone interacts with the software. If the app is closed, some state may be saved so it can be restored later.
Keep exploring
Other languages
Loading MyLeoNes™…