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.
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.
varstops here. - Block scope: declared with
letorconstinside any{ }(anif, afor, 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.
Press Run (⌘ Enter) to see what happens.Inside the if, the engine looks up inner and finds it right here in the block scope.
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.
What does this print?
let x = 1;
function show() {
let x = 2;
if (true) {
let x = 3;
}
return x;
}
console.log(show(), x);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.
What does this print?
const name = "global";
function speak() {
return name;
}
function run() {
const name = "local";
return speak();
}
console.log(run());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.
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.
makeCounter() returns, why is count not garbage collected?The classic var in a loop bug
This is the most famous closure puzzle. Predict it before reading on.
What does this print?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}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.
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 called | this 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).
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.
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());Three fixes, all common in real code:
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.
Press Run (⌘ Enter) to see what happens.What is this inside show for each call?
Counter factory
Write makeCounter(start = 0, step = 1) that returns an object with four functions, all sharing private state through a closure:
increment()addsstepand returns the new valuedecrement()subtractsstepand returns the new valuereset()goes back tostartand returns itvalue()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(); // 10memoize
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- 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/bindtarget, a new object withnew, orundefined. - bind
- Returns a new function whose
this(and optionally leading arguments) is permanently fixed.