Problem Statement
Show three ways to declare variables (var, let, const) and compare scope and reassignment rules.
Explanation
var — function-scoped, hoisted to undefined, can be redeclared and reassigned; easy to leak outside blocks. let — block-scoped, cannot be redeclared in the same scope, can be reassigned; preferred for mutable bindings. const — block-scoped, not reassignable; the binding is constant but the referenced object can still be mutated. Prefer const by default, use let when you must reassign, avoid var.
Code Solution
SolutionRead Only
// var — function scope
function f() {
if (true) { var x = 1; }
console.log(x); // 1 (leaks out of block)
}
// let — block scope
if (true) { let y = 2; }
// console.log(y); // ❌ ReferenceError
// const — binding cannot change
const cfg = { a: 1 };
// cfg = {} // ❌ reassign
cfg.a = 2; // ✅ mutate property