JS enginescoreletmaxLivesconst1let score = 0;2const maxLives = 3;3score = score + 10;4score = score + 5;5console.log(score, maxLives);6maxLives = 4;Console15 3score.js:5TypeError:score.js:6Assignment to constant variable.0300 + 10101010 + 5151534
Back: the JavaScript engine, and memory with one box per variableFront: the program score.js and the consoleTokens: each line, the values 0, 3, 10, 15 and 4, the sums and the errorAt the back, the JavaScript engine and memory, which starts empty. In front, the program score.js and the console. let and const each make a named box. On lines 3 and 4 the old value of score hops out to the engine, the sum is worked out, and the answer hops back in. console.log prints 15 3. Line 6 tries to change the const maxLives: the 4 bounces off its padlock and the console shows a TypeError. The box is a simplification. The ECMAScript specification calls a variable a binding: a name that refers to a value, kept in an environment record for that block of code. Strictly, the binding exists from the start of its block but cannot be used until its line runs (the temporal dead zone).

A program with two variables

  1. Here is a six-line program that keeps a game score. The JavaScript engine runs it top to bottom, one line at a time. Memory starts empty: no variable exists until a line makes one.

Making variables

Changing and reading

A const stays put

Good habits

What happens

// step 1/10 · program
file     score.js, 6 lines
engine   runs line 1, then line 2, ...
memory   score = (none yet)   maxLives = (none yet)

The box is a simplification. The ECMAScript specification calls a variable a binding: a name that refers to a value, kept in an environment record for that block of code. Strictly, the binding exists from the start of its block but cannot be used until its line runs (the temporal dead zone). Chrome and Node.js (the V8 engine) print "TypeError: Assignment to constant variable."; Firefox says "invalid assignment to const 'maxLives'". The error happens when line 6 runs, so lines 1 to 5 have already run and 15 3 is printed first.