Skip to main content

How do let and const differ from var?

1. Main differences

Criterionvarletconst
ScopeFunction or globalBlock ({ ... })Block ({ ... })
HoistingHoisted and initialized to undefinedHoisted, but not initialized (error if accessed before declaration)Hoisted, but not initialized (error if accessed before declaration)
Re-declarationAllowed within the same scopeErrorError
Reassigning the valueAllowedAllowedNot allowed
Added to the window object (in the browser)Yes (window.varName)NoNo

2. Scope

var - function scope

javascript
if (true) { var a = 10; } console.log(a); // 10 (accessible outside the block!)

let / const - block scope

javascript
if (true) { let b = 20; const c = 30; } console.log(b); // ReferenceError console.log(c); // ReferenceError

let and const only "live" inside a {} block.


3. Hoisting (variable hoisting)

All variables are "hoisted" to the top of their scope, but var is initialized with the value undefined, while let and const fall into the Temporal Dead Zone (TDZ).

javascript
console.log(a); // undefined (var is hoisted) var a = 5; console.log(b); // ReferenceError (in the TDZ) let b = 10; console.log(c); // ReferenceError (in the TDZ) const c = 15;

4. Re-declaration and reassignment

javascript
var x = 1; var x = 2; // allowed console.log(x); // 2 let y = 1; let y = 2; // SyntaxError: Identifier 'y' has already been declared const z = 1; z = 2; // TypeError: Assignment to constant variable

5. Behavior with objects and arrays under const

const protects the reference, not the contents.

javascript
const user = { name: 'Tim' }; user.name = 'Alex'; // the property can be changed console.log(user.name); // 'Alex' user = {}; // The object itself cannot be reassigned

6. Behavior in the browser (global variables)

javascript
var x = 10; let y = 20; const z = 30; console.log(window.x); // 10 console.log(window.y); // undefined console.log(window.z); // undefined

var adds the variable to the global object (window, globalThis), while let and const do not, which makes the code safer.


7. Summary - how to use them

SituationWhat to useWhy
The variable needs to changeletSafer than var, with block scope
The variable should not changeconstExplicitly shows immutability
Legacy code (pre-ES6)varOutdated, use only to support old projects

A simple rule of thumb

const - by default. let - when you need to change the value. var - never use it in modern code.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.