Skip to content
LumenaryAcademy
Foundations 55 min

Scope, closures and this

Which variables a function can see, why it remembers them, and the one keyword whose meaning depends on the call.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Functions that remember

In the last lesson, makeRounder(2) returned a function that still knew factor was 100 long after makeRounder had returned. That is not a trick; it is how every JavaScript function works, and it is the single most important idea in the language after "functions are values". It is how event handlers know which item was clicked, how modules keep private state, and how libraries such as React keep track of what a component remembers.

The same lesson promised an explanation of this, the keyword that refers to "the current object". In most languages it is boring. In JavaScript it is decided anew at every call, which makes it the source of one of the most common bugs in the language. By the end of this lesson both ideas will be predictable, and you will know the three fixes professionals use.

DefinitionsH

Scope

Definition— scope and lexical scoping

The scope of a binding is the region of code where its name refers to it. JavaScript is lexically scoped: you can work out which declaration a name refers to just by reading the source, looking outward from the place the name is used to the nearest enclosing block, then function, then module, then global scope that declares it.

Modern JavaScript has four kinds of scope: block scope (any { ... }, for let, const and class), function scope (parameters, and var), module scope (top-level declarations in an ES module are private to that file unless exported), and global scope (shared by everything; avoid adding to it).

javascript
// Lexical scope: a name refers to the nearest enclosing declaration.
const level = "module";

function outer() {
  const level = "outer function";      // shadows the module-level name
  function inner() {
    return `inner sees: ${level}`;     // looks outward: finds outer's level
  }
  {
    const level = "block";             // a third, separate binding
    console.log("block sees:", level);
  }
  return inner();
}

console.log(outer());
console.log("module sees:", level);

// The temporal dead zone: a let/const exists from the start of its block,
// but reading it before its declaration has run is an error.
function early() {
  try {
    console.log(answer);
  } catch (err) {
    console.log(err.name, "-", err.message);
  }
  const answer = 42;
  return answer;
}
console.log(early());

// var ignores blocks and is hoisted as undefined.
function oldStyle() {
  console.log("before:", total);
  {
    var total = 10;                    // belongs to the whole function
  }
  return total;
}
console.log("after:", oldStyle());
text
block sees: block
inner sees: outer function
module sees: module
ReferenceError - Cannot access 'answer' before initialization
42
before: undefined
after: 10

Three declarations named level coexist; an inner one shadows the outer ones within its region and leaves them untouched. inner finds outer's level, not the block's, because the block is not on the path outward from where inner was written. Where a function is called never matters for ordinary variables.

The second part shows the temporal dead zone. A const or let binding exists from the start of its block (it is "hoisted"), but it is uninitialised until its declaration runs, and touching it before then throws. That is a feature: it turns the use of a variable before it has a value into a loud error. The third part shows why var was replaced: it ignores the block, belongs to the whole function, and silently reads as undefined before its assignment.

IntuitionH

Closures

Definition— closure

A closure is a function together with the scope in which it was created. A function can read and update the variables of every enclosing scope, and it keeps that access for as long as the function itself exists, even after the enclosing function has returned.

The phrase "keeps that access" is precise: a closure holds the variables themselves, not copies of their values at the moment of creation. If the variable changes, the closure sees the change; if the closure changes it, everyone sharing it sees the change.

javascript
// A closure: a function together with the variables it can see where it was created.
function makeCounter(start = 0) {
  let count = start;                   // private: nothing outside can touch it
  return {
    increment() { count += 1; return count; },
    reset() { count = start; },
    get value() { return count; },
  };
}

const visits = makeCounter();
const downloads = makeCounter(100);
visits.increment();
visits.increment();
downloads.increment();
console.log(visits.value, downloads.value);
visits.reset();
console.log(visits.value, "count" in visits);

// once: wrap a function so it runs only the first time.
function once(fn) {
  let done = false;
  let result;
  return (...args) => {
    if (!done) {
      done = true;
      result = fn(...args);
    }
    return result;
  };
}
const init = once((name) => { console.log("initialising for", name); return 7; });
console.log(init("Chen"), init("Fatima"));

// memoize: remember earlier answers.
function memoize(fn) {
  const cache = new Map();
  return (n) => {
    if (!cache.has(n)) cache.set(n, fn(n));
    return cache.get(n);
  };
}
let calls = 0;
const fib = memoize((n) => {
  calls++;
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
});
console.log(fib(70), "computed with", calls, "calls");
text
2 101
0 false
initialising for Chen
7 7
190392490709135 computed with 71 calls

Each call to makeCounter creates a new count, so visits and downloads are independent. The returned object's three methods all close over the same count, which is truly private: "count" in visits is false, and no code outside can read or change it except through those methods. (get value() is a getter: reading visits.value runs it. Lesson five covers getters.)

once and memoize are higher-order functions built on closures, and versions of both appear in nearly every utility library. memoize turns the naive Fibonacci function, which would need more than six hundred trillion calls to reach fib(70), into one that computes each value once: 71 calls. It works because the inner function's recursive calls go through fib, the memoised wrapper, which consults the shared cache.

Analogy, not a formal construction

A closure is like a letter written in one house and posted to another, which carries a key to the house it was written in. Wherever the letter goes, it can still open that house's drawers and change what is in them, and anyone else holding the same key sees the changes.

Closures come from Scheme, and behind Scheme from Alonzo Church's lambda calculus, in which functions are the only values there are; see Lumenary Math's lambda calculus. Before ES modules existed, JavaScript programmers built private module state entirely out of closures, with the "immediately invoked function expression", (function () { ... })(). You will still find it at the top of old library files.

Worked examplesH

The classic loop bug

Because closures capture variables and not values, the difference between var and let becomes visible as soon as a loop creates functions:

javascript
// The classic loop bug: one shared var versus a fresh let per iteration.
const withVar = [];
for (var i = 0; i < 3; i++) {
  withVar.push(() => i);
}

const withLet = [];
for (let j = 0; j < 3; j++) {
  withLet.push(() => j);
}

console.log(withVar.map((f) => f()));
console.log(withLet.map((f) => f()));

// The same bug with timers, which run after the loop has finished.
for (var k = 0; k < 3; k++) {
  setTimeout(() => console.log("var timer sees", k), 0);
}
for (let m = 0; m < 3; m++) {
  setTimeout(() => console.log("let timer sees", m), 0);
}
text
[ 3, 3, 3 ]
[ 0, 1, 2 ]
var timer sees 3
var timer sees 3
var timer sees 3
let timer sees 0
let timer sees 1
let timer sees 2

With var there is exactly one i for the whole function. All three arrows close over that one variable, and by the time they run, the loop has left it at 3. With let, the specification creates a fresh binding for every iteration of a for loop, copying the current value into it, so each arrow captures its own j. The timers show the same thing in its most common real-world form: setTimeout(fn, 0) runs fn only after the current code has finished (lesson eight explains exactly when), so every var timer sees the final value. This bug was common enough before 2015 to have its own folklore; let made it disappear.

ExplanationH

this: decided at the call

Inside an ordinary function (not an arrow), this is an implicit extra parameter, and it is filled in by the way the function is called:

How the function is calledthis is
obj.method(...)obj, the object before the dot
fn(...), a plain callundefined in strict mode (every module and class body); the global object in old sloppy-mode scripts
fn.call(x, ...) or fn.apply(x, [...])x, chosen explicitly
fn.bind(x)creates a new function whose this is permanently x
new Fn(...)a brand-new object, which the call returns
an arrow function, called any waywhatever this was where the arrow was written; arrows have no this of their own
javascript
// `this` is decided by how a function is called, not where it is written.
function whoAmI() {
  return this === undefined ? "undefined" : this.name;
}

const ada = { name: "Ada", whoAmI };
const grace = { name: "Grace", whoAmI };

console.log(ada.whoAmI());              // method call: this is the object before the dot
console.log(grace.whoAmI());
console.log(whoAmI());                  // plain call in strict mode: this is undefined
console.log(whoAmI.call(grace));        // call: choose this explicitly
console.log(whoAmI.apply(ada, []));     // apply: the same, with arguments as an array

const boundToAda = whoAmI.bind(ada);    // bind: a new function with this fixed
grace.borrowed = boundToAda;
console.log(grace.borrowed());          // still Ada: bind wins over the dot

// new: this is a brand-new object, which is returned automatically.
function Point(x, y) {
  this.x = x;
  this.y = y;
}
console.log(new Point(2, 3));

// Arrow functions have no this of their own: they use the surrounding one.
const team = {
  name: "Lumen",
  members: ["Ama", "Bo"],
  describe() {
    return this.members.map((m) => `${m} of ${this.name}`);
  },
};
console.log(team.describe());
text
Ada
Grace
undefined
Grace
Ada
Ada
Point { x: 2, y: 3 }
[ 'Ama of Lumen', 'Bo of Lumen' ]

The same function, whoAmI, gives four different answers depending only on the call. Note the contrast with ordinary variables, which are resolved lexically: this is the one name in the language resolved dynamically. Arrows opt out of that and resolve this lexically like any other name, which is exactly what you want in the describe method: the arrow passed to map sees the this of describe, which is team. Before arrows existed, people wrote const self = this; above the callback to get the same effect.

The lost this

The bug happens when a method is taken off its object and called later, which is what passing it as a callback does:

javascript
// The "lost this" bug: passing a method separates it from its object.
const timer = {
  label: "kettle",
  seconds: 0,
  tick() {
    this.seconds += 1;
    return `${this.label}: ${this.seconds}s`;
  },
};

const tick = timer.tick;                       // just the function, no object
try {
  tick();
} catch (err) {
  console.log(err.name, "-", err.message);
}

// Three fixes, all common in real code.
const viaArrow = () => timer.tick();           // 1. wrap the call in an arrow
const viaBind = timer.tick.bind(timer);        // 2. bind the method to its object
console.log(viaArrow(), "|", viaBind());

class Stopwatch {                              // 3. a class field holding an arrow
  label = "stopwatch";
  seconds = 0;
  tick = () => {
    this.seconds += 1;
    return `${this.label}: ${this.seconds}s`;
  };
}
const watch = new Stopwatch();
const detached = watch.tick;
console.log(detached(), "|", [1, 2].map(watch.tick).join(", "));
text
TypeError - Cannot read properties of undefined (reading 'seconds')
kettle: 1s | kettle: 2s
stopwatch: 1s | stopwatch: 2s, stopwatch: 3s

timer.tick evaluated without a call is just the function; the link to timer exists only in the expression timer.tick(). Called plainly, this is undefined, and reading this.seconds throws. In the browser, the same thing happens with button.addEventListener("click", widget.onClick), or with setTimeout(widget.refresh, 1000).

The three fixes: wrap the call in an arrow at the point where you pass it (simplest, and most common); bind the method once, typically in a constructor; or define the method as a class field holding an arrow function, so each instance gets its own function with this captured at construction. The third costs one function per instance rather than one shared on the prototype, which matters only when you create very many objects.

Worked examplesH

Closures and strict mode in real code

Handlers that remember their item

Here is the shape of code you will write the first week you build a web page. It runs in a browser, so it is shown without output; lesson nine explains document and events.

javascript
for (const product of products) {
  const button = document.createElement("button");
  button.textContent = `Add ${product.name}`;
  button.addEventListener("click", () => addToBasket(product.id));
  list.append(button);
}

Each arrow passed to addEventListener is a closure over that iteration's product (a for...of loop with const creates a fresh binding each time, just like for with let). Minutes later, when someone clicks the third button, its arrow still knows which product it belongs to. No lookup table, no id attribute to parse: the closure is the memory.

Debouncing

Search boxes often wait until the user pauses typing before sending a request. The standard tool is a debounce wrapper, and it is nothing but a closure over a timer:

javascript
function debounce(fn, waitMs) {
  let timerId;                          // shared by every call to the wrapper
  return (...args) => {
    clearTimeout(timerId);              // cancel the previous pending call
    timerId = setTimeout(() => fn(...args), waitMs);
  };
}

const search = debounce((text) => console.log("searching for", text), 300);
// Typing "lim", "lima", "lima p" quickly calls search three times,
// but only the last call survives the 300 ms pause.

Every call to the returned arrow sees the same timerId, so each one can cancel the call scheduled by the one before. Libraries such as Lodash ship debounce and its cousin throttle; writing your own once is the best way to understand them.

Stale closures

The flip side of "a closure keeps the variables it was created with" is that a function created earlier keeps seeing the variables of that earlier moment. In user-interface frameworks that recreate their state variables on every update (React's function components are the best-known example), a timer or event handler created during one update can keep reading the values from that update, long after the screen shows newer ones. This is called a stale closure, and framework documentation spends real effort on it. When a callback seems to see old data, ask: when was this function created, and which variables did it capture?

Strict mode

Several rules in this lesson, such as this being undefined in a plain call, hold in strict mode, which ES5 introduced in 2009 to fix mistakes without breaking old pages: old scripts stay in "sloppy mode" unless they opt in with the line "use strict"; at the top. ES modules and class bodies are always strict. Among other things, strict mode makes assignment to an undeclared variable throw a ReferenceError instead of quietly creating a global (a typo like totl = 5 used to do that), makes writes to read-only properties throw instead of failing silently, forbids duplicate parameter names, and removes the confusing with statement. Every program in this course is a module, so you get all of this automatically; in the browser, <script type="module"> does the same.

Common misconceptionsH

Common misconceptions

Misconception

"A closure copies the variables' values when it is created." It keeps the variables themselves. That is why all the var arrows saw 3, and why increment and reset in makeCounter affect each other.

Misconception

"this refers to the function itself," or "to the object the function was defined in." Neither. For an ordinary function it is whatever the call supplies; for an arrow it is the this of the surrounding code. The place a method is written matters only for arrows.

Misconception

"Always use arrow functions, then." Arrows are right for callbacks. They are wrong as object methods that need the object ({ total: () => this.items.length } sees the module's this, which is undefined), wrong as constructors (they cannot be used with new), and wrong as event handlers that rely on this being the element. Use method syntax for methods and arrows for the functions you pass around.

Misconception

"Closures leak memory." A closure keeps alive the variables it uses, which is the point. It becomes a leak only when something long-lived, such as a global list of event handlers, keeps holding a closure you no longer need. Removing the handler releases everything it captured.

Exercises

Exercises

Work each one out on paper first: which binding does each name refer to, and how is each function called?

1. Scope, closures and this

Warm-upComputational

What does this print?

const x = "global";
function show() {
  const x = "function";
  {
    const x = "block";
  }
  return x;
}
console.log(show(), x);

2. Scope, closures and this

Warm-upComputational

What does this print?

function makeCounter() {
  let n = 0;
  return () => ++n;
}
const c1 = makeCounter();
const c2 = makeCounter();
c1();
c1();
console.log(c1(), c2());

3. Scope, closures and this

CoreComputational

What number does this print?

const fs = [];
for (var i = 0; i < 3; i++) {
  fs.push(() => i * 10);
}
console.log(fs[0]());

4. Scope, closures and this

CoreComputational

This runs as an ES module. What does it print?

const user = {
  name: "Zainab",
  regular() { return typeof this; },
  arrow: () => typeof this,
};
console.log(user.regular(), user.arrow());

5. Scope, closures and this

CoreComputational

What does this print?

const f = function () { return this.n; }.bind({ n: 1 });
console.log(f.call({ n: 2 }));

6. Scope, closures and this

CoreHuman

widget.refresh is an ordinary method that uses this. Which of these call it later with this set to widget? Choose all that apply.

Choose all that apply

7. Scope, closures and this

StretchComputational

What happens when this function is called?

function report() {
  const message = `Total: ${total}`;
  let total = 5;
  return message;
}
Choose one

Further reading and resources