Skip to content

Lesson 10 of 50JavaScript in depth

Scope, Closures and this

Predict which variable a function sees, use closures for private state, and know what this points to in every call.

16 min read0/6 questions

You can now write functions and shape data with arrays and objects. The next question is which variables a function can see, and what this means when it runs. Closures power React hooks, event handlers, debouncing, memoisation and every module pattern. this is behind the classic "cannot read properties of undefined" error when you pass a method as a callback. Both are guaranteed interview topics, usually as "what does this code print?" puzzles, so this lesson is built around predicting output.

Scope: where a name is visible

Scope is the region of code where a variable can be used. JavaScript has three levels you meet daily:

  • Global / module scope: declared at the top of a file.
  • Function scope: declared inside a function. var stops here.
  • Block scope: declared with let or const inside any { } (an if, a for, a bare block).

When code uses a name, the engine looks in the current scope, then the enclosing one, and so on outward until the global scope. That chain is the scope chain. Inner code can see outer variables; outer code cannot see inner ones.

JavaScript
const app = "RazorCode"; // module scope function outer() { const level = "outer"; // function scope if (true) { const inner = "block"; // block scope console.log(app, level, inner); // sees all three } console.log(typeof inner); // the block variable is gone} outer();
Output
Press Run (⌘ Enter) to see what happens.
Scope chain for the code above
module scopeappif block scopeinnerouter() function scopelevelroot

Inside the if, the engine looks up inner and finds it right here in the block scope.

1/4

A variable in an inner scope with the same name as an outer one shadows it: the inner one wins inside its block, and the outer one is untouched.

Predict the outputJavaScript

What does this print?

let x = 1;
function show() {
let x = 2;
if (true) {
  let x = 3;
}
return x;
}
console.log(show(), x);
Need a nudge? Hints walk you through it.

Lexical scope

JavaScript uses lexical scope: a function sees the variables where it was written, not where it is called. You can work out what a function can see just by reading the code, which is what "lexical" (about the text) means.

Predict the outputJavaScript

What does this print?

const name = "global";
function speak() {
return name;
}
function run() {
const name = "local";
return speak();
}
console.log(run());
Need a nudge? Hints walk you through it.

Closures

Here is the key consequence. When a function is created inside another function, it keeps access to the outer function's variables even after the outer function has returned. The function plus the variables it remembers is called a closure.

JavaScript
function makeCounter() { let count = 0; // private: nothing outside can touch it directly return { increment: () => ++count, current: () => count, };} const a = makeCounter();const b = makeCounter();a.increment();a.increment();b.increment();console.log(a.current(), b.current());console.log(a.count); // not a property: the variable is hidden
Output
Press Run (⌘ Enter) to see what happens.

Each call to makeCounter creates a fresh count, and the returned functions close over their own copy. That gives you truly private state without classes. It is how React's useState remembers values between renders, how once and memoize work, and how libraries hid internals before modules existed.

Quick check
After makeCounter() returns, why is count not garbage collected?
Need a nudge? A hint rules out a wrong answer.

The classic var in a loop bug

This is the most famous closure puzzle. Predict it before reading on.

Predict the outputJavaScript

What does this print?

for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
Need a nudge? Hints walk you through it.

The fix is to use let. A let in a for header creates a new binding for every iteration, so each callback closes over its own i.

JavaScript
for (let i = 0; i < 3; i++) { setTimeout(() => console.log("let:", i), 0);} // Keep the program alive until the timers fire (the runner stops when your code ends)await new Promise((resolve) => setTimeout(resolve, 10));
Output
Press Run (⌘ Enter) to see what happens.

Before 2015 people fixed it with an immediately invoked function, (function (j) { ... })(i), which created a new scope per iteration by hand. You may still see that in old code.

this: decided by the call

this is a special variable that every regular function gets. Unlike other variables, its value is not lexical. It is set when the function is called, based on how the call is written. Four rules cover almost everything:

How it is calledthis is
obj.method() (method call)obj, the thing before the dot
fn() (plain call)undefined in strict mode (classes, modules, this course's runner); the global object in old sloppy scripts
fn.call(x), fn.apply(x), fn.bind(x)x, set explicitly
new Fn()the brand new object being created

Arrow functions are the exception: they have no this of their own. They use the this of the scope they were written in, exactly like any other variable (lexical this).

JavaScript
const user = { name: "Ada", regular() { return this?.name; }, later() { // the arrow takes this from later(), which was called on user return [1].map(() => this.name)[0]; },}; console.log(user.regular()); // method call: this = userconst detached = user.regular;console.log(detached()); // plain call: this = undefinedconsole.log(user.later());
Output
Press Run (⌘ Enter) to see what happens.

Losing this

The bug you will actually hit: passing a method as a callback. setTimeout(user.regular, 0) or button.addEventListener("click", user.regular) passes the function alone. When it is later called as a plain function, this is gone.

Predict the outputJavaScript

What does this print?

const cart = {
items: 2,
count() {
  return this.items;
},
};
const fn = cart.count;
try {
console.log(fn());
} catch (e) {
console.log(e.name);
}
console.log(cart.count());
Need a nudge? Hints walk you through it.

Three fixes, all common in real code:

JavaScript
const cart = { items: 2, count() { return this.items; },}; const bound = cart.count.bind(cart); // 1. bind returns a new function with this lockedconsole.log(bound()); const wrapped = () => cart.count(); // 2. wrap it in an arrow that makes a method callconsole.log(wrapped()); // 3. call / apply run the function once with an explicit thisconsole.log(cart.count.call({ items: 7 }));console.log(cart.count.apply({ items: 9 }, []));
Output
Press Run (⌘ Enter) to see what happens.

call and apply differ only in how they pass arguments: fn.call(thisArg, a, b) vs fn.apply(thisArg, [a, b]). bind does not call the function; it returns a new one.

new

Calling a regular function with new creates an empty object, sets this to it, runs the function, and returns the object. That is how constructors worked before classes, and classes still do this underneath. Arrow functions cannot be used with new.

JavaScript
function Person(name) { this.name = name;}const p = new Person("Sam");console.log(p.name, p instanceof Person);
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/5 matched

What is this inside show for each call?

Choose an item, then its match on the other side.
ChallengeEasy

Counter factory

Write makeCounter(start = 0, step = 1) that returns an object with four functions, all sharing private state through a closure:

  • increment() adds step and returns the new value
  • decrement() subtracts step and returns the new value
  • reset() goes back to start and returns it
  • value() returns the current value

The count itself must not be visible as a property on the returned object.

const c = makeCounter(10, 5);
c.increment(); // 15
c.increment(); // 20
c.reset();     // 10
JavaScript
function makeCounter(start = 0, step = 1) { // Keep the count in a local variable and return functions that use it. return {};}
ChallengeMedium

memoize

Write memoize(fn). It returns a function that behaves like fn but caches results: calling it again with the same arguments returns the stored result without calling fn.

Build the cache key from all arguments with JSON.stringify(args). Results like 0, false or undefined must be cached too.

const slowSquare = (n) => { /* expensive */ return n * n; };
const fastSquare = memoize(slowSquare);
fastSquare(9); // computes 81
fastSquare(9); // returns 81 from the cache
JavaScript
function memoize(fn) { // Keep a Map from argument key to result in a closure. return fn;}
Key terms
scope chain
The nested scopes the engine searches outward through to resolve a variable name.
lexical scope
A function sees the variables where it was written, not where it is called.
closure
A function together with the outer variables it captured. Those variables stay alive as long as the function does.
shadowing
An inner variable with the same name as an outer one hides the outer one within its scope.
this
Set per call for regular functions: the object before the dot, an explicit call/bind target, a new object with new, or undefined.
bind
Returns a new function whose this (and optionally leading arguments) is permanently fixed.