JavaScript theorytheory 0/50 · 0%
Fundamentals · easy

2. let, const and var

Block scope and why `var` is retired.

`let` and `const` are block-scoped: they exist only inside the nearest `{ }`. `const` forbids reassignment of the binding, though the object it points at can still be mutated. `var` is function-scoped and hoisted, which causes surprising bugs.

const chain = "Base";
let block = 1;
block += 1;

const cfg = { rpc: "https://…" };
cfg.rpc = "other"; // allowed — the binding did not change

Default to `const`, reach for `let` when a value genuinely changes, and never write `var` in new code.

Check your understanding

  1. 1. What does `const` prevent?

  2. 2. What scope does `var` have?

  3. 3. Which should you default to?