Before ES6, JavaScript only had the var keyword for variable declarations. ES6 introduced let and const to improve scope management and prevent common bugs.
let and const are block scoped variables that help write safer and cleaner code.
Why let and const?
Problems with var:
- Function-scoped, not block-scoped
- Can be redeclared
- Hoisting behavior can cause bugs
let and const solve these problems by:
- Restricting scope to block {}
- Preventing accidental redeclaration
- Making code more predictable
let Keyword
Syntax
let variableName = value;Example
let name = "Nikhil";console.log(name); // Nikhil
name = "JavaScript";console.log(name); // JavaScriptKey Point
- let variables can be reassigned
- let variables cannot be redeclared in the same scope
- Block scoped: only exists inside { }
Example: Block Scope
if (true) { let age = 25; console.log(age); // 25}console.log(age); // ReferenceError: age is not definedlet variables are restricted to the block
Const Keyword
Syntax
const variableName = value;Example
const pi = 3.14;console.log(pi); // 3.14
pi = 3.14159; // Error: Assignment to constant variableKey Point
- cont variables cannot be reassigned
- Must be initialized during declaration
- Block scoped: only exists inside { }
Example: Object & Array with const
const prevents reassignment, not mutation.
const person = { name: "Nikhil" };person.name = "JavaScript"; // ✅ Allowedconsole.log(person.name); // JavaScript
const arr = [1, 2, 3];arr.push(4); // ✅ Allowedconsole.log(arr); // [1, 2, 3, 4]- You cannot reassign person or arr entirely
- But you can modify their contents
Difference Between var, let and const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Redeclare | Yes | No | No |
| Reassign | Yes | Yes | No |
| Hoisting | Yes | Yes (no init) | Yes (no init) |
| Best Use | Legacy | Mutable vars | Constants / Immutable refs |
When to Use
- const - for constants, objects, arrays (when reference won’t change)
- let - for loop counters, mutable variables
- Avoid var in modern code
Two Minute Drill
- let = block scoped, can reassign, cannot redeclare
- const = block scoped, cannot reassign, prevents redeclaration
- Objects / arrays declared with const can be mutated
- Always prefer const for safer code
- var is function scoped legacy, avoid in modern JS
