var, let, & constVariables are named containers used to store data values in memory. JavaScript provides three keywords for variable declaration: var (ES5 legacy), let (ES6 block-scoped), and const (ES6 block-scoped constant).
flowchart TD
Decl["Variable Declaration"] --> VarCheck{"Which Keyword?"}
VarCheck -- "var" --> FunctionScope["Function / Global Scoped (Hoisted as undefined)"]
VarCheck -- "let" --> BlockScope1["Block Scoped (Reassignable, Temporal Dead Zone)"]
VarCheck -- "const" --> BlockScope2["Block Scoped (Read-Only Binding, Must Initialize)"]
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function / Global | Block ({}) |
Block ({}) |
| Hoisting | Hoisted (initialized as undefined) |
Hoisted (Uninitialized - TDZ) | Hoisted (Uninitialized - TDZ) |
| Re-declaration | Allowed in same scope | TypeError in same scope |
TypeError in same scope |
| Re-assignment | Allowed | Allowed | TypeError (Immutable binding) |
// Demonstrating var vs let vs const scope & mutability
// 1. var function-scope issue demo
function testVarScope() {
var x = 10;
if (true) {
var x = 20; // Re-declares and overwrites x in function scope!
console.log(`Inside block (var x): ${x}`); // 20
}
console.log(`Outside block (var x): ${x}`); // 20 (Polluted!)
}
testVarScope();
// 2. let block-scope behavior
function testLetScope() {
let y = 10;
if (true) {
let y = 20; // Isolated to this block
console.log(`Inside block (let y): ${y}`); // 20
}
console.log(`Outside block (let y): ${y}`); // 10 (Safe!)
}
testLetScope();
// 3. const object mutation
const userConfig = { theme: "dark", lang: "en" };
userConfig.theme = "light"; // Allowed! Object properties are mutable.
console.log("Updated userConfig:", userConfig);
// userConfig = {}; // Un-commenting throws TypeError: Assignment to constant variable.
const: Use const for all variable declarations by default.let When Mutation is Required: Use let only when you know the variable value will be reassigned (e.g., loop counters, accumulators).var Entirely: Legacy var scoping leads to subtle hoisting bugs and unexpected global scope leaks.What will console.log(a) print if placed BEFORE var a = 5; vs BEFORE let a = 5;?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.