let vs const vs var in JavaScript

HTML, CSS & JS 2 min read
Short answer

Use const for everything, switch to let only when you genuinely reassign the variable, and never use var. var is function-scoped and hoisted, which produces bugs the other two cannot.

javascript
const name = 'Dom';       // cannot be reassigned
let count = 0;            // can be reassigned
count += 1;

var old = 'avoid';        // function-scoped, hoisted — legacy

#const does not mean immutable

It means the binding cannot be reassigned. The object itself is still mutable:

javascript
const config = { theme: 'dark' };
config.theme = 'light';        // fine
config = {};                   // TypeError

For genuine immutability, Object.freeze(config) — though that is shallow too.

#Why var is a problem

It ignores block scope:

javascript
if (true) { var x = 1; }
console.log(x);      // 1 — leaked out of the block

if (true) { let y = 1; }
console.log(y);      // ReferenceError — correct

It hoists as undefined:

javascript
console.log(a);      // undefined — no error, which hides the bug
var a = 1;

console.log(b);      // ReferenceError: Cannot access 'b' before initialization
let b = 1;

let and const are also hoisted, but into a "temporal dead zone" that throws if you touch them early. Erroring loudly beats undefined propagating silently.

#The classic loop bug

javascript
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));   // 3, 3, 3
}

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));   // 0, 1, 2
}

var creates one binding shared by every iteration. let creates a fresh binding each time. This single difference is why let exists.