JavaScript fundamentals

5 concepts · 10 practice questions

Scope and closures

let and const are scoped to the block they are declared in; var is scoped to the whole function. A let or const binding exists from the start of its block but cannot be touched until its declaration runs (the temporal dead zone). A closure is a function that keeps access to the variables of the scope it was created in. It holds the variable itself, not a snapshot, so it sees later changes. let in a for loop creates a fresh binding per iteration, which is why it fixes the classic timer bug.

for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j)); // 0 1 2

function makeCounter() {
  let count = 0; // private: only the returned functions can reach it
  return { inc: () => ++count, get: () => count };
}

Also covered

How this is bound
Prototypes and classes
Equality and coercion
ES modules

Sign in to read the rest and take the 10-question test.

Sign in to continue