JavaScript Interview Question: var vs let vs const and Hoisting
Short answer: var is function-scoped and hoisted with the value undefined. let and const are block-scoped and can't be used before their declaration (the temporal dead zone). const can't be reassigned.
Scope
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1 - var ignores blocks
console.log(b); // ReferenceError - b only exists inside the block
Hoisting and the temporal dead zone
console.log(x); // undefined - declaration hoisted, value not
var x = 5;
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;
All declarations are hoisted, but let/const stay uninitialised until their line runs. Function declarations are hoisted completely, which is why you can call them before they appear.
const doesn't mean immutable
const user = { name: 'Asha' };
user.name = 'Ravi'; // fine - the object can change
user = {}; // TypeError - the binding can't be reassigned
const frozen = Object.freeze({ name: 'Asha' }); // shallow immutability
Other differences
varcan be re-declared in the same scope;let/constcan't.- Top-level
varcreates a property on the global object in scripts;let/constdon't. letin aforloop gets a fresh binding per iteration (see the closure loop question).
What to use
const by default, let when you need to reassign, and no var in modern code.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.