Skip to content
Lesson 8 of 10 · JavaScript for Beginners

Scope and closures

Know where variables live, and use closures to make functions that remember.

18 min

Scope is the part of a program where a name can be used.

javascript9 lines
const outside = "visible everywhere below";

function demo() {
  const inside = "only inside demo";
  if (true) {
    let blockOnly = "only inside these braces";
  }
  // blockOnly is not defined here
}

const and let are block-scoped: they live inside the nearest { }. A function can see variables from the scopes around it, but not the other way round. The old var is function-scoped and ignores blocks, which is why it causes bugs.

A function remembers the variables that were around it when it was created, even after the outer function has finished. That remembered package is a closure:

javascript13 lines
function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

const next = makeCounter();
next();   // 1
next();   // 2
const other = makeCounter();
other();  // 1   (its own count)

count is private: nothing outside can reach it, but the returned function can still read and change it. Each call to makeCounter makes a fresh count.

Closures let you build functions to order (makeMultiplier(3) gives a "times 3" function), keep state private, and write callbacks that remember context. Almost every event handler on a web page is a closure.

javascript5 lines
const fns = [];
for (var i = 0; i < 3; i++) {
  fns.push(() => i);
}
fns.map(f => f());   // [3, 3, 3], not [0, 1, 2]

With var there is one i shared by every function; by the time they run it is 3. With let each round gets its own i, giving [0, 1, 2].

Analogy

A closure is like a backpack. When a function is created, it packs the variables it can see. Wherever the function travels afterwards, it carries that backpack and can still open it.

Where the analogy breaks down

A backpack holds copies of things. A closure holds the **variables themselves**, so if the outer variable changes, the function sees the new value, and two functions sharing one variable share its changes.

Exercise3 checks
javascript

Write makeMultiplier(factor) that returns a function. The returned function takes a number and returns it multiplied by factor.

makeMultiplier(3)(4) is 12.

Your code must satisfy

  • makeMultiplier(3)(4)→12triple
  • makeMultiplier(0.5)(10)→5half
  • [makeMultiplier(2)(5), makeMultiplier(10)(5)]→[10,50]two separate
starter code3 lines
function makeMultiplier(factor) {
  
}
Exercise3 checks
javascript

Write makeCounter(start) that returns a function. Each time the returned function is called it adds 1 to the count and returns the new count, beginning after start. Two counters must not share their count.

If const c = makeCounter(10), then c() is 11, and the next c() is 12.

Your code must satisfy

  • (() => { const c = makeCounter(10); c(); return c(); })()→12counts up
  • (() => { const c = makeCounter(0); return [c(), c(), c()]; })()→[1,2,3]from zero
  • (() => { const a = makeCounter(0); const b = makeCounter(100); a(); a(); return [a(), b()]; })()→[3,101]independent
starter code3 lines
function makeCounter(start) {
  
}
Exercise4 checks
javascript

makeGetters(n) should return n functions where the function at position k returns k. So makeGetters(3).map(f => f()) should be [0, 1, 2]. Fix the loop.

What it does now

makeGetters(3).map(f => f()) returns [3, 3, 3].

Your code must satisfy

  • makeGetters(3).map(f => f())→[0,1,2]three
  • makeGetters(1).map(f => f())→[0]one
  • makeGetters(5).map(f => f())→[0,1,2,3,4]five
  • makeGetters(0).map(f => f())→[]zero
starter code7 lines
function makeGetters(n) {
  const fns = [];
  for (var i = 0; i < n; i++) {
    fns.push(function () { return i; });
  }
  return fns;
}
Common misconception

“Variables declared with `var` inside an `if` or loop block stay inside it, like `let`.”

Most languages work that way, and the braces look like a boundary.

What is actually true

var ignores blocks and is scoped to the whole function. A var inside a loop leaks out, and one variable is shared by every closure made in the loop.

How to catch yourself

Use `const` and `let` only. If you inherit code with `var`, expect surprises.

  • const and let are block-scoped; a function sees the scopes around it, never the reverse.
  • A closure is a function plus the variables it remembered from where it was created.
  • Closures give you private state and functions made to order.
  • Use let/const, not var, so each loop round gets its own variable.
Check yourself

Scope checks.

1Multiple choice

Where can a let variable declared inside if (x) { ... } be used?

  • AOnly inside those braces
  • BAnywhere in the file
  • COnly in the whole function
  • DNowhere
2Multiple choice

function f() { let n = 0; return () => ++n; } const g = f(); g(); g(); What does the next g() return?

  • A0
  • B1
  • C3
  • D2
3Multiple choice

Do const a = f() and const b = f() share one private count?

  • AYes, always
  • BNo, each call makes a fresh one
  • COnly with var
  • DOnly in arrow functions
4Multiple choice

Which prints [0, 1, 2] for fns.map(f => f()) in the loop-trap example?

  • A`var i`
  • B`let i`
  • CNeither
  • DBoth
5Fill the blanks

A function together with the variables it remembers is called a .

Capitalisation, spacing and punctuation are ignored when grading.

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of JavaScript for Beginners is planned around your week. Free.