Hi! I'm Sage, your BloggerSpace assistant. Ask me to find blogs, recommend topics, or explain how the platform works β I'll pull live data and share clickable links.
Powered by Gemini Β· may occasionally be wrong
JavaScript
#165 var vs let vs const in JavaScript
Teekam Singh23 Aug 202526 views
JavaScriptInterview Questions
πΉ var vs let vs const in JavaScript
Feature
var
let
const
Scope
Function-scoped
Block-scoped ({})
Block-scoped ({})
Hoisting
β Hoisted → initialized as undefined
β Hoisted → but in Temporal Dead Zone (TDZ) until initialized
β Hoisted → but in TDZ until initialized
Re-declaration
β Allowed in same scope
β Not allowed in same scope
β Not allowed
Re-assignment
β Allowed
β Allowed
β Not allowed (must assign value at declaration)
Global object property
β Attached to window (in browsers)
β Not attached
β Not attached
Best use case
Legacy code (avoid using in modern JS)
Variables that will change values
Constants that never change (IDs, config, etc.)
πΉ Examples
1. Scope Difference
if (true) {
var x = 10;
let y = 20;
const z = 30;
}
console.log(x); // β 10 (var is function-scoped)
console.log(y); // β ReferenceError (block-scoped)
console.log(z); // β ReferenceError (block-scoped)
2. Hoisting
console.log(a); // β undefined (hoisted with default undefined)
var a = 5;
console.log(b); // β ReferenceError (TDZ)
let b = 10;
console.log(c); // β ReferenceError (TDZ)
const c = 15;
3. Re-declaration & Re-assignment
// var
var name = "Dev";
var name = "John"; // β allowed
console.log(name); // John
// let
let age = 25;
// let age = 30; // β SyntaxError
age = 30; // β allowed
// const
const city = "Delhi";
// const city = "Mumbai"; // β SyntaxError
// city = "Mumbai"; // β TypeError
4. Global Object Property (browser example)
var a = 100;
let b = 200;
const c = 300;
console.log(window.a); // β 100
console.log(window.b); // β undefined
console.log(window.c); // β undefined
πΉ Summary
var → function-scoped, hoisted, re-declarable → β avoid in modern JS.
let → block-scoped, re-assignable, safer → β use for variables that change.
const → block-scoped, immutable binding, must initialize → β use for constants.