Three keywords, one decision rule: const by default, let when you must reassign, var never. Here is why.
The differences
- Scope: var is function-scoped; let/const are block-scoped (respect
{ }) - Hoisting: var hoists as
undefined(silent bugs); let/const throw if used before declaration - Reassignment: const blocks it; let allows it
The classic trap
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 โ
new binding per loop
}const nuance interviewers probe
const arr = [1, 2]; arr.push(3); // โ fine โ contents can change arr = [9]; // โ TypeError โ the BINDING is constant
const prevents reassignment, not mutation. Freeze contents with Object.freeze(). Full lesson: Variables.