Skip to the workspace
Pebellslearn by building
All about Variables  ›  Lesson

var, let and const

All about Variables 12 min

javascript / var, let and const

Explore each scene at your own pace.

01 · var, let and const

var, let and const

var, let and const

const creates a binding that cannot be reassigned. let creates a binding that can be reassigned. var has older function-scoped behavior.

Choose whether a name may receive another value; const does not freeze an object’s contents.

Build a reading-session panel. Change the minutes in code, compare calculating with assigning, and see which values your panel keeps.

Opening your JavaScript project…

Reference and extra examples

Open this whenever you want a fuller explanation. Your project above is the main activity.

Reference model

These authored snapshots explain the example below; they are not a trace of your edited project.

Walk through the modelvar, let and constAuthored snapshots of the example; use Run below to test the code.
title"Quiet mornings"
reads0
The names are associated with their starting values.
1 of 3

Follow one example

javascript

reads starts at 0. The right-hand side reads that value and adds 1; assignment stores the result back under reads. title is not reassigned. Use const for names you do not reassign and let where reassignment is required. Study var’s scope after learning functions, rather than treating it as another spelling of let.

Predict, change and check

Predict: If reads is declared with const, which instruction fails: its declaration or reads = reads + 1?

Test your explanation: Change let reads to const reads, observe the reassignment error, then restore let. A failed assignment does not undo instructions that already completed.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Binding changes and object changes

Use const when the binding should keep referring to the same value and let when reassignment is part of the algorithm. const does not freeze the referenced object: const article = {saved:false} still permits article.saved = true. A repeated declaration in the same lexical scope is different from a new declaration in a nested scope.

In a loop that installs callbacks, let creates per-iteration bindings for the loop variable; a var-based loop commonly shares one function-scoped binding. Test callbacks after the loop, not only during it. For an empty or uninitialized value, do not assume const supplies a default: a const declaration needs an initializer.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.