Understanding the real uses and differences between var, let, and const is fundamental to modern JavaScript.
var is function-scoped, meaning it is accessible anywhere within the function it is declared in. let and const are block-scoped, meaning they are only accessible within the block {} they are declared in.
var a = 10let b = 20const c = 30
console.log(a) ✓console.log(b) ✗ ReferenceError
function example() {
if (true) {
var a = 10;
let b = 20;
const c = 30;
}
console.log(a); // 10 (var is function-scoped)
// console.log(b); // ReferenceError (let is block-scoped)
// console.log(c); // ReferenceError (const is block-scoped)
}
var gets hoisted and set to undefined, so we can access it before the declaration line. But let and const sit in a Temporal Dead Zone until the code reaches the declaration line — trying to use them before that will throw a ReferenceError.
console.log(a); // undefined (var is hoisted and initialized)
// console.log(b); // ReferenceError (temporal dead zone)
var a = 1;
let b = 2;
const cannot be reassigned after declaration. However, if the value is an object or array, the properties or elements inside it can still be modified.
const user = { name: "Manish" };
user.name = "Pika"; // This works, object properties can be modified
// user = {}; // TypeError: Assignment to constant variable
In simple language, use const by default, use let when you need to reassign, and avoid var in modern JavaScript.