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.
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) |
A block in JavaScript is any code enclosed within curly braces { ... } (such as if conditions, for loops, or standalone blocks).
var Leaking:let and const:let vs. constlet when values must change:const for values that should NOT be reassigned:const with Objects and Arraysconst prevents reassigning the variable identifier binding, but does not make the internal contents of an object or array immutable!
Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope before code execution.
var: Variables are hoisted and initialized with undefined:let and const: Variables are hoisted, but remain in the Temporal Dead Zone (TDZ) until the line of declaration is reached:Top engineering teams follow the 90/10 Rule:
const for 90% of your variables by default (objects, arrays, functions, constants).let only when you know the variable will be reassigned (loop counters, toggles, accumulating scores).var in modern codebases.let and const have?const?const (e.g. const user = { name: "Alex" }; user.name = "Sam";)?var avoided in modern JavaScript development?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Setting up Environment: VSCode, Live Server | Data Types |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.