Var vs let vs const in JavaScript
🧠 Introduction:
“Hey developers! Today we’re diving deep into one of the most common JavaScript questions: What’s the difference between var, let, and const? Understanding these is crucial for writing modern, bug-free JavaScript. Let’s get into it!”
📌 1. var — The Old Way
- Introduced in ES5 (before ES6).
- Function-scoped, not block-scoped.
- Can be re-declared and updated.
- Gets hoisted to the top of its scope with
undefined.
function test() {
console.log(a); // undefined (due to hoisting)
var a = 10;
console.log(a); // 10
}- ❗ Downsides:
- Can lead to bugs due to hoisting.
- Scope leakage due to lack of block scoping.
🆕 2. let — Modern and Safer
- Introduced in ES6 (2015).
- Block-scoped.
- Can be updated, but not re-declared in the same scope.
- Also hoisted, but not initialized.
function test() {
// console.log(b); // ReferenceError
let b = 20;
console.log(b); // 20
}- ✅ Use
letwhen you expect the value to change.
🔒 3. const — Immutable Binding
- Also introduced in ES6.
- Block-scoped like
let. - Cannot be re-assigned or re-declared.
const c = 30;
// c = 40; // TypeError- ❗ However, objects declared with
constare not immutable — just the binding is.
const obj = { name: 'Dev' };
obj.name = 'Coder'; // ✅ Allowed- ✅ Use
constby default unless the variable needs to change.
🆚 Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function Scope | Block Scope | Block Scope |
| Hoisting | Yes (undefined) | Yes (TDZ*) | Yes (TDZ*) |
| Re-declare | Yes | No | No |
| Re-assign | Yes | Yes | No |
| Temporal Dead Zone (TDZ) | No | Yes | Yes |
TDZ (Temporal Dead Zone): Time between hoisting and declaration where the variable can’t be accessed.
Should I stop using var?
✅ Yes, prefer let and const — they are block-scoped and safer.
When should I use let?
Use let when the variable’s value is expected to change.
When should I use const?
Use const when the variable will not be reassigned. This helps with code predictability.
Can const objects be mutated?
Yes, the reference is constant, not the object itself.
What happens if I access let or const before declaration?
You get a ReferenceError due to the Temporal Dead Zone.
No comments yet! You be the first to comment.
