VCF

Unit 4 · Thinking like a programmer

Why changing one variable doesn’t change another

A variable holds a value, not a formula. score = bonus + 5 works out the sum once and stores the result. Changing bonus afterwards leaves score exactly as it was.

The mix-up

What people often think

“Changing bonus later also changes score, because score was made from bonus.”

What the tutor says

Line 3 worked out 0 + 5 and stored the result, 5. The box holds a value, not a formula, so changing bonus later leaves score alone.

If you copy a number onto a sticky note, does the note change when the original does?

How it works

Think of a variable as a labelled box. The right side of = is worked out first, and only the result goes in the box, like copying a number onto a sticky note. The note does not change when the original does.

The same idea explains a common bug: visits + 1 on its own line works out a new number and throws it away. To change the box, put the result back in it: visits = visits + 1.

An example

What worksJavaScript
let bonus = 0;
let score = bonus + 5;  // score is 5
bonus = 10;
console.log(score);     // still 5

let visits = 3;
visits + 1;             // worked out, then thrown away
visits = visits + 1;    // visits is now 4
The box keeps the value it was given.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “Writing visits + 1 adds one to the box.”

    visits + 1 works out the new number, then throws it away. Put it back in the box: visits = visits + 1.

Practise it with a tutor watching

Variables are labelled boxes

Store values in variables, update them, and tell assigning apart from comparing.

15 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.