The mental model
Picture your computer's memory as a huge warehouse shelf. Every time you create a variable, JavaScript grabs an empty box, sticks a name label on the front, and drops a value inside.
-
The label is the variable name, like
score. -
The contents are the value, like
120. -
letmakes an open box. You can swap what's inside later. -
constmakes a sealed box. Once it's packed, you can't put something new in.
Whenever your code says the label, JavaScript walks to the shelf, opens that box, and uses whatever is inside.
What happens, box by box
Each numbered step matches a numbered comment in the code below.
The code in action
// 1. Grab an open box, label it "playerName", put "Ada" inside
let playerName = "Ada";
// 2. Same box, new contents. No "let" here: the box already exists
playerName = "Grace";
// 3. A sealed box. Use const for values that should never change
const maxLives = 3;
// Say the label, get what's inside
console.log(playerName); // "Grace"
console.log(maxLives); // 3
// 4. Try to repack the sealed box... JavaScript refuses
// maxLives = 5; // TypeError: Assignment to constant variable.
-
Tip: Reach for
constfirst. Switch toletonly when you know the value will change (a score, a counter). -
Tip: Write
letorconstonly once per box. Writing it again tries to build a second box with the same label, and JavaScript will complain. -
Tip: You may still see
varin older tutorials. It's the old way to make boxes; stick withletandconst.
Quick challenge: Open your browser console (F12), type
let snack = "apple"; snack = "mango"; snackand press Enter. Then tryconst treat = "apple"; treat = "mango";and read the error. Which box was sealed?

Top comments (0)