Three keywords create variables in JavaScript, and two of them exist mostly so you can avoid the third. Learn the modern rules and scope stops being scary.
Use const by default, let when the value must change, and never var in new code. const and let are block-scoped (they live inside the nearest { }); var is function-scoped and hoisted, which causes classic bugs.
const site = "BitWithBite"; // can't be reassigned
let score = 0; // can change
score += 10; // fine
// site = "other"; // TypeError: Assignment to constant
const user = { name: "Ada" };
user.name = "Alan"; // OK! const locks the BINDING,
// not the object's contentsif (true) {
let inside = "visible only here";
const also = "me too";
}
// console.log(inside); // ReferenceError — gone outside the block
for (let i = 0; i < 3; i++) { /* i lives only in the loop */ }
// console.log(i); // ReferenceErrorconsole.log(ghost); // undefined (not an error!) — var hoists
var ghost = "boo";
for (var j = 0; j < 3; j++) {}
console.log(j); // 3 — var leaks out of the loop!
// same code with let would throw helpful errors insteadconst userName = "ada"; // camelCase — the JS standard const MAX_LIVES = 3; // ALL_CAPS for true constants const _internal = "private-ish"; // const 2fast = "no"; // can't start with a digit // const class = "no"; // reserved word
let x = 1; let x = 2; in the same scope is a SyntaxErrorconst by default — it documents that the binding never changes. Switch to let only when you actually reassign, like counters and accumulators.
Declarations are processed before code runs. var variables are hoisted and initialized to undefined; let/const are hoisted but locked in a 'temporal dead zone' until their line runs, so using them early throws an error.
const freezes the variable binding, not the value. To make an object's contents immutable use Object.freeze(obj).
No — there is no situation in modern JavaScript where var is required. It survives only in legacy code.