Variables: var, let, const
Variables: var, let, const
A variable is a named storage container in memory used to hold data values that your program can read, manipulate, and update. In modern JavaScript (ES6+), choosing the correct variable declaration keyword (const, let, or var) is fundamental to writing predictable, bug-free code.
1. Evolution of Variable Declarations
2. The Big Three: var vs let vs const
| Feature | var (Legacy) | let (Modern Mutable) | const (Modern Constant) |
|---|---|---|---|
| Scope | Function Scope | Block Scope { } | Block Scope { } |
| Reassignable? | Yes | Yes | No (TypeError) |
| Re-declarable in same scope? | Yes (Accidental overwrites!) | No (SyntaxError) | No (SyntaxError) |
| Must initialize on declaration? | No | No | Yes (Must give value!) |
| Hoisting Behavior | Hoisted with undefined | Hoisted into Temporal Dead Zone (TDZ) | Hoisted into Temporal Dead Zone (TDZ) |
3. Scope Mechanics: Function Scope vs. Block Scope
A block in JavaScript is any code enclosed within curly braces { ... } (such as if conditions, for loops, or standalone blocks).
The Danger of var Leaking:
The Safety of let and const:
4. Reassignment: let vs. const
Use let when values must change:
Use const for values that should NOT be reassigned:
Critical Nuance: const with Objects and Arrays
const prevents reassigning the variable identifier binding, but does not make the internal contents of an object or array immutable!
5. Hoisting and the Temporal Dead Zone (TDZ)
Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope before code execution.
- With
var: Variables are hoisted and initialized withundefined:
- With
letandconst: Variables are hoisted, but remain in the Temporal Dead Zone (TDZ) until the line of declaration is reached:
6. Industry Golden Rule: 90/10 Rule
Top engineering teams follow the 90/10 Rule:
- 1Use
constfor 90% of your variables by default (objects, arrays, functions, constants). - 2Use
letonly when you know the variable will be reassigned (loop counters, toggles, accumulating scores). - 3Never use
varin modern codebases.
Practice Quiz
let and const have?const?const (e.g. const user = { name: "Alex" }; user.name = "Sam";)?var avoided in modern JavaScript development?Data Types
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Setting up Environment: VSCode, Live Server | Data Types |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.