Skip to content

Under the hood

What is a variable in coding? A simple explanation

A variable is a named box that holds a value your program can use and change. See how variables work, with JavaScript examples and common mistakes.

By the Amphicode team · · Facts checked · 8 min read

Key takeaways

  • A variable is a named container for a value. The name stays the same; the value inside can change while the program runs.
  • In JavaScript you create a variable with `let` (a value that will change) or `const` (a value that won't).
  • `=` puts a value into a variable. It does not mean "is equal to" the way it does in maths.
  • Most beginner bugs with variables come from spelling, capital letters, using a variable before it has a value, or mixing up `=` and `===`.
  • Spotting the variables is one of the quickest ways to understand code, including code an AI tool wrote for you.

A variable in coding is a name that holds a value, such as a score, a player's name or whether a game is over. The program can read that value, use it in sums and messages, and change it while it runs. Think of a box with a label on it: the label is the variable's name and the thing inside is its value.

This guide is for learners aged about 9 to 14 who are meeting variables for the first time, and for parents helping with homework. It uses JavaScript, the language of web pages, with a quick look at Python.

What is a variable, in plain words?

MDN, the reference guide many web developers use, puts it like this in its beginner guide to variables: "A variable is a container for a value."

Picture a row of boxes on a shelf. Each box has a label (score, lives, playerName) and something inside it (0, 3, "Zap"). When your code says score, the computer goes to the box labelled score and looks at what's inside. When your code says "put 10 in score", it swaps what's in the box.

That's the whole idea. Variables let a program remember things while it runs, so it can keep count, keep track of what the player typed, or decide what to show next.

A variable in JavaScript, line by line

Here's a tiny program about a space hamster. Read it slowly before you look at the explanation.

let snacks = 0;
const petName = "Nibbles";

snacks = snacks + 1;
snacks = snacks + 1;

console.log(petName + " has had " + snacks + " snacks.");

What happens:

LineWhat it doesWhat's in the boxes afterwards
let snacks = 0;Makes a box called snacks and puts 0 in itsnacks: 0
const petName = "Nibbles";Makes a box called petName that will never changesnacks: 0, petName: "Nibbles"
snacks = snacks + 1;Reads snacks (0), adds 1, puts the answer (1) backsnacks: 1
snacks = snacks + 1;Reads snacks (1), adds 1, puts 2 backsnacks: 2
console.log(...)Joins the pieces into one message and shows it(no change)

The message shown is Nibbles has had 2 snacks.

Two words are worth knowing. Creating the box is called declaring the variable. Putting the first value into it is called initialising it. MDN's guide explains that you can do both at once, as let snacks = 0; does.

Why snacks = snacks + 1 isn't nonsense

In maths, "x = x + 1" can never be true. In code, = isn't a statement that two things are equal: it's an instruction. Python's official tutorial says it directly: "The equal sign (=) is used to assign a value to a variable." So the computer works out the right-hand side first (the old value plus one), then stores the answer in the box on the left.

let, const and var: which should I use?

JavaScript has three ways to make a variable:

  • `let` for a value that will change, like a score or a timer.
  • `const` for a value you set once and never replace, like a pet's name or a button you found on the page.
  • `var`, an older way you'll still see in old code and tutorials.

MDN's variables guide recommends using let rather than var, because var is "confusing and error-prone", and gives a simple rule: "Use const when you can, and use let when you have to."

If you try to put a new value into a const, the browser stops with an error. In Chrome and other browsers built on the same V8 engine, the console shows TypeError: Assignment to constant variable., according to MDN's page on that error. That error is useful: it tells you something changed that you'd said wouldn't.

One subtlety for older learners: const stops you swapping the box's contents for something else, but if the box holds a list or an object, the MDN reference for const notes you can still add, change or remove what's inside that list or object.

What can a variable hold?

A variable can hold different kinds of value, called data types. The ones beginners meet first:

TypeExampleUsed for
Numberlet lives = 3;Scores, counts, sizes
String (text)let planet = "Zorb";Names, messages, anything typed
Booleanlet gameOver = false;Yes/no, on/off, true/false
Array (list)let snacks = ["seed", "pea"];Several values in order
Objectlet robot = { name: "Bolt", power: 7 };A thing with named parts

MDN describes JavaScript as a "dynamically typed language": you don't have to say in advance which type a variable will hold. Some other languages make you say so.

The same idea in Python

Python makes variables without a keyword:

snacks = 0
snacks = snacks + 1
print(snacks)

The idea is identical: a name, a value, and = to put the value in. If you use a name before giving it a value, Python's tutorial shows the error you'll get, here for a name n: NameError: name 'n' is not defined. If you've used variables in Scratch, they work the same way in text code; our guide to moving from Scratch to real code covers the jump.

Common variable mistakes (and how to spot them)

These are common beginner mistakes. Each one has a clue you can look for.

MistakeExampleThe clue
Different capital letterslet myScore = 0; then myscore = 5;An error that the name isn't defined, or a value that never changes. MDN notes variable names are case-sensitive.
Starting a name with a numberlet 2ndPlayer = "Ada";An error straight away. MDN's guide says names can't start with a number.
Using = when you meant ===if (lives = 0)The if behaves strangely, and lives is quietly changed to 0. One = puts a value in; === compares two values.
Forgetting to store the answersnacks + 1; on its ownNothing changes. The sum is worked out and thrown away. Write snacks = snacks + 1;.
Quotes round a variable nameconsole.log("snacks");The word "snacks" appears instead of the number. Quotes make text; no quotes means "look in the box".
Replacing a constconst lives = 3; then lives = 2;TypeError in the console. Use let if the value needs to change.

For a step-by-step way to track down problems like these, see our guide to debugging for beginners.

Try it: predict the output

Before running code, predict what it will do. It's the first step of the PRIMM method for reading code. What does this show?

let coins = 5;
coins = coins + 10;
coins = coins - 3;
console.log("Coins: " + coins);

Answer: Coins: 12. If you said 5, look again at what each = line stores.

Variables in AI-written code

When an AI coding tool writes code for you, the variables are a good place to start reading it. Before you accept a change, ask:

  1. What does each variable hold? Good names (highScore, isMuted) make this obvious. Names like x, temp or data2 are worth asking the tool to rename.
  2. Where does each one change? Follow a variable from where it's made to every line that gives it a new value. Surprising changes are where bugs hide.
  3. Is any variable never used? Extra code is extra places for bugs to hide. Remove it, then check the app still works.
  4. Does any variable hold something secret? A password or key written straight into front-end code can be read by anyone. Our guide to API keys and secrets explains where those belong instead.

There's more on this in our checklist for reviewing AI-generated code.

How Amphicode teaches variables

Amphicode teaches variables in the Level 1 course First Web Pages on the Amphicode pathway, in a lesson on JavaScript variables and click events. Learners read a short example, then change a working page: a button that feeds a space hamster, where each click adds one to a snacks variable and the page shows the new count. Its simpler explanation for younger readers uses the "labelled box" picture, and the lesson explains let for values that change and const for things that stay the same.

That course is part of Code Craft, Amphicode's optional hand-coding strand. Learners can build apps with Amphicode's AI helper and coding agent without it, and switch to writing code themselves whenever they're curious. For how JavaScript fits alongside HTML and CSS, see HTML, CSS and JavaScript explained.

Variables in schools

Variables are part of many school computing courses. In England, for example, the national curriculum for computing expects pupils at Key Stage 2, in primary school, to "work with variables and various forms of input and output". Other countries' curricula differ, so check what your child's school uses.

Frequently asked questions

Is a variable in coding the same as a variable in maths?

Not quite. In maths, a variable such as x usually stands for a number you're trying to find, and an equation states a fact. In code, a variable is a named place to store a value, and `=` is an instruction to put a value there, which is why `x = x + 1` makes sense in a program.

Do variables remember things after I close the page?

No. A variable only lasts while the program is running, so a score kept in a variable is gone when the page closes or reloads. To keep information for next time, apps save it somewhere more permanent, such as a database. Our guide to [what a database is](/blog/what-is-a-database) explains how.

What makes a good variable name?

A good name says what the value is, so someone reading the code (including you next week) can follow it: `lives`, `playerName`, `isGameOver`. MDN's guide suggests "lower camel case" for JavaScript, where words are joined and each new word starts with a capital letter, and warns against names that start with a number or use JavaScript's reserved words.

Why does my variable say undefined?

Because it has been made but not given a value yet. `let lives;` creates the box but leaves it empty, so `console.log(lives)` shows `undefined`; MDN's guide shows the same thing. Give the variable a starting value when you make it, such as `let lives = 3;`.

Sources

  1. Storing the information you need — Variables (opens in a new tab) — MDN Web Docs
  2. const (opens in a new tab) — MDN Web Docs
  3. TypeError: invalid assignment to const "x" (opens in a new tab) — MDN Web Docs
  4. An Informal Introduction to Python (opens in a new tab) — Python Software Foundation
  5. National curriculum in England: computing programmes of study (opens in a new tab) — Department for Education

How we write: Amphicode articles are researched and drafted with the help of AI tools, then checked in a separate review step against the sources listed above before they are published, and re-checked when they are updated. Rules and products change, so check official pages for your country before acting on anything here. This article is general information, not legal advice. Spotted a mistake? Email hello@amphicode.com.