What is the difference between var, let and const in JavaScript?
Quick answer
var is function-scoped and can be redeclared; let and const are block-scoped, and const cannot be reassigned after it is set.
var is function-scoped, is hoisted and initialised to undefined, and can be redeclared in the same scope. let and const are block-scoped: they only exist inside the nearest pair of curly braces.
let and const are also hoisted, but they stay in the temporal dead zone until the line where they are declared, so using them earlier throws a ReferenceError instead of silently giving undefined.
const prevents reassigning the variable, not mutating the value. A const array or object can still be changed by pushing to it or setting a property. Use const by default, let when you need to reassign, and avoid var in new code.
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1 (var ignores the block)
console.log(b); // ReferenceError: b is not defined
const list = [1, 2];
list.push(3); // allowed, the array is mutated
list = []; // TypeError: Assignment to constant variableKey points
- var: function scope, hoisted as undefined, can be redeclared
- let: block scope, temporal dead zone, cannot be redeclared in the same scope
- const: like let, but the binding cannot be reassigned
Questions interviewers ask next
- What is the temporal dead zone?
- Why does a var inside a for loop behave differently with setTimeout?