Lesson 3
let, const & var
Build a practical mental model for let, const & var and use it in working JavaScript.
By the end, you will be able to…
- Explain let, const & var in your own words
- Use let, const & var in a small program
- Recognize and debug a common failure mode
Build the mental model
const creates a binding that cannot be reassigned, let creates one that can, and var predates block scoping entirely, attaching to the nearest function instead. Defaulting to const documents your intent: this value will not change.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Reassignment bugs — a value silently changing somewhere far from where you're reading it — are far easier to rule out when most of your bindings are const.
Real-world example
Linters in every serious JavaScript codebase enforce const-by-default and flag var as legacy for exactly this reason.
Common mistakes
- Using let everywhere out of habit instead of defaulting to const
- Trying to reassign a const binding and being surprised by the TypeError
- Mixing var into modern code and being surprised by function-scoping
Try it yourself
Challenge
Fix the snippet so it uses const where nothing is reassigned and let only where it is.
Knowledge check
Which declaration should you reach for by default in new JavaScript code?
Summary
Prefer const; use let only when a binding must change; avoid var in new code.