What is the difference between var, let, and const in JavaScript?
var is function-scoped and hoisted; let and const are block-scoped. Use const by default, let when you need to reassign, and avoid var.
JavaScript
Overview
`var`, `let`, and `const` all declare variables, but they differ in scope, hoisting behaviour, and reassignability. `let` and `const` were introduced in ES2015 to fix the surprising behaviour of `var`.
Key Points
- •`var` is function-scoped (or global), hoisted to the top of its function, and can be re-declared.
- •`let` is block-scoped `{}`, not accessible before declaration (temporal dead zone), and can be reassigned.
- •`const` is block-scoped, cannot be reassigned, but object/array contents can still be mutated.
- •Use `const` by default; use `let` only when you need to reassign. Never use `var` in new code.
- •Hoisting: `var` declarations are moved to the top and initialised as `undefined`; `let`/`const` are hoisted but not initialised.
Examples
Scope difference: var leaks out of blocks
javascriptif (true) {
var x = 'var'; // accessible outside the block
let y = 'let'; // block-scoped, only inside {}
}
console.log(x); // 'var'
console.log(y); // ReferenceError: y is not definedconst prevents reassignment, not mutation
javascriptconst user = { name: 'Alice' };
user.name = 'Bob'; // OK mutating the object
user = {}; // TypeError: Assignment to constant variableThe var hoisting trap
javascriptconsole.log(a); // undefined (not an error var is hoisted)
var a = 5;
console.log(b); // ReferenceError temporal dead zone
let b = 5;Pro Tip
Default to `const`. If you get an error about reassignment, switch that one declaration to `let`. This makes your intent clear: `const` means "this binding never changes", `let` means "this will change".