Variables — let · const · var
Variables — let · const · var
🎯 After reading this lesson
After reading this lesson, you will be able to confidently do the following 3 things.
- ▸✅ Why
varis dangerous (function scope · hoisting) - ▸✅ What TDZ (Temporal Dead Zone) is
- ▸✅ How to choose between
const/letbased on reassignment needs
Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.
What is a variable?
The Core in One Line
Variable = a container that stores a value under a name. JS has 3 keywords — var·let·const — which coexist for historical reasons. Bottom line: const first, let when needed, never var.
const — Set Once, Done
The most frequently used keyword. 95% of variables are fine with const. Reassignment is usually unnecessary.
> ⚠️ Common confusion: const only prohibits reassignment — internal modification is still allowed:
let — When You Truly Need to Change the Value
For loop counters, running totals, and other cases where the value must change. Start with const and switch to let only when truly necessary.
var — The Old Keyword, Don't Use It
Before 2015, JS only had var. But:
- ▸Function scope — a declaration inside
ifapplies to the entire function - ▸Hoisting — can be used regardless of declaration position (causes confusion)
- ▸Re-declaration allowed — declaring the same name twice produces no error
These unpredictable traits cause bugs. You'll only see it in legacy code now.
Block Scope — The Real Value of let·const
let·const are only valid within the block ({}) they are declared in. This means predictable behavior + no variable name collisions.
Naming Conventions
Quick Summary
Start with const and switch to let only when you truly need to.
⚡ Try It Yourself — const · let · var
🤖 Try Asking AI Like This
Once you know the concepts in this lesson, you can give AI specific instructions. Instead of a vague 'fix this,' you can make requests with vocabulary — and that is where token savings begin.
- ▸"Replace all var in this code with const/let"
- ▸"Analyze reassignment possibilities and reorganize with const as the default"
- ▸"Diagnose potential hoisting issues in this code"
Why This Reduces Tokens
Without knowing the concepts, even after receiving an AI response you have to ask 'What does that mean?' again. That follow-up question is what consumes tokens. Learn the concept once, and the conversation ends in a single exchange.