Variables & Assignment

A variable is a name attached to a value the program is keeping track of. Assignment — usually written with = — stores a value under that name; later, using the name reads the value back out.

score = 5            store 5 under the name "score"
score = score + 10   read score (5), add 10, store 15 back

The crucial, sometimes confusing point: score = score + 10 isn't a claim that the two sides are equal. It's a command — compute the right side, then put the result into the box on the left. The name stays the same; the value inside changes. What kind of value a variable can hold is governed by its type.

Deep dive · Where the value actually lives: the stack and the heap

A running program keeps its data in two regions of memory. Small, short-lived values — a loop counter, a number, a reference — sit on the stack: a region that grows and shrinks automatically as functions are called and return, making it very fast but tied to the function's lifetime. Larger or longer-lived data — a list that grows, an object whose size isn't known ahead of time — is put on the heap, a general pool you allocate from explicitly (or that a garbage collector manages for you).

So a variable often doesn't hold the big thing directly; it holds a small value on the stack that points to the real data on the heap. That's why, in many languages, copying a variable copies the pointer, not the data — and two variables can end up referring to the very same object.

hierarchy prerequisite related

See the full map →