DEV Community

Cover image for Labeled Boxes: How JavaScript Remembers Things
Ayekple Clemence
Ayekple Clemence

Posted on

Labeled Boxes: How JavaScript Remembers Things

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.
  • let makes an open box. You can swap what's inside later.
  • const makes 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

Four steps: create a let box, swap its value, seal a const box, and a rejected reassignment

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.
Enter fullscreen mode Exit fullscreen mode
  • Tip: Reach for const first. Switch to let only when you know the value will change (a score, a counter).
  • Tip: Write let or const only 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 var in older tutorials. It's the old way to make boxes; stick with let and const.

Quick challenge: Open your browser console (F12), type let snack = "apple"; snack = "mango"; snack and press Enter. Then try const treat = "apple"; treat = "mango"; and read the error. Which box was sealed?

Top comments (0)