All 28 lessons ▾
Inside JavaScript · Lesson 10 of 28
Closures, Line by Line
So, a function's box is deleted when it returns. So how can its variable still be used, long after it's gone? That's a closure! Now let's watch one happen.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- Functions are values: you can return them
- A closure: a function + its lexical environment
- It remembers the parent's variables after the parent returns
- It holds references, not copies
- It reaches every level of the scope chain
- Used for privacy, modules, currying, memoize, timers
Part 1Functions are values
Okay, closures. If you've ever been to a JavaScript interview, you've heard this word. And most people can only half explain it. So today, you'll understand it completely, line by line. But first, we need one small idea. In JavaScript, a function is a value, just like a number or a string. So you can store a function in a variable, pass it into another function, and even return it from a function. Now remember this. Returning a function is where all the magic begins.
1var shout = function () {2 console.log("Hey!");3};4 5run(shout);6 7function make() {8 return shout;9}So here's that idea in code. On the first line, a function is stored in a variable called shout, just like a number would be. On line five, shout is passed into another function, run, as an argument. And inside make, shout is returned, like any other value. Stored, passed, returned. So a function is just a value. Now let's return a function that was created inside another function, and see what happens.
1function makeGreeter() {2 var name = "Riya";3 function greet() {4 console.log("Hi " + name);5 }6 return greet;7}8 9var sayHi = makeGreeter();10sayHi();Hi Riya
So look at this program. A function makeGreeter, which has a variable name, Riya, and an inner function greet, that says hi to name. And makeGreeter doesn't call greet. It returns it. Global is pushed, and phase one stores makeGreeter, and sayHi as undefined. Line nine calls makeGreeter. A brand new context is pushed, and its local memory gets name and greet. Line two, name becomes Riya. Line six, return greet. So greet is handed back, and makeGreeter is done. Its execution context is deleted, and popped off the stack. Gone. Back on line nine, sayHi receives the function greet. So now sayHi holds greet.
Now line ten calls sayHi. A new context is pushed, for greet. So line four logs hi plus name. But wait. greet has no name in its own memory. Its parent was makeGreeter, and makeGreeter's box was deleted! So this should be an error. But no. It prints hi Riya. Then greet is popped. How?! makeGreeter is gone, its box was deleted, and greet still remembers Riya.
So this is a closure. Remember this definition. A closure is a function, bundled together with its lexical environment. Now when greet was created inside makeGreeter, it didn't come alone. It came bundled with a reference to the variables around it, its lexical environment. So when makeGreeter returned greet, it didn't just return a function. It returned the function, plus its surroundings. That bundle is the closure. Now I'll say it once more, in plain words. A closure is a function that remembers the variables of the place where it was created.
So here's a picture to remember it forever. Think of the function as a person leaving home. Before greet leaves makeGreeter, it packs a backpack. And in that backpack, it carries the variables from home that it needs. So here, just name. Not everything in the house, only what it uses. Now greet can travel anywhere in your program, and whenever it needs name, it opens its backpack. The house is gone, but the backpack goes along. So that backpack is the closure.
1function makeGreeter() {2 var name = "Riya";3 return function () {4 console.log("Hi " + name);5 };6}And now you'll often see this written in a shorter way. So instead of creating greet, and then returning it, people return the function directly. return function, and then the body. Don't panic when you see this. It's exactly the same thing. A function is created inside makeGreeter, and handed back, with its backpack. Same closure, just fewer lines.
Part 2A reference, not a copy
Now, here's something interesting that most people miss. Does the backpack hold a copy of the value, or the variable itself? So let's test it.
1function makeGreeter() {2 var name = "Riya";3 function greet() {4 console.log("Hi " + name);5 }6 name = "Kabir";7 return greet;8}9 10makeGreeter()();Hi Kabir
So this time, name starts as Riya. Then, after greet is created, line six changes name to Kabir. Then greet is returned, and line ten calls it straight away. So, what does it print? It prints hi Kabir! Not Riya. Because the backpack doesn't hold a copy of the value. It holds a reference to the variable itself.
So remember this. A closure keeps a reference to the variable, not a frozen copy of its value. Whatever the variable holds at the moment the function runs, that's what it sees. Now think of it as a window into the room, not a photograph of it. A photo freezes the past, a window shows you what's there right now. And this one detail is behind a very famous interview question with setTimeout, which we'll crack in the next episode. So keep it in your mind.
Part 3Closures go all the way up
And a closure doesn't just remember one level up. It remembers every level of its scope chain. So watch.
1function city() {2 var pin = 302001;3 function street() {4 var house = 42;5 function door() {6 console.log(house, pin);7 }8 door();9 }10 street();11}12city();42 302001
So three functions, one inside the other. city has a pin code. street, inside city, has a house number. And door, inside street, logs both. Line twelve calls city, city calls street, and street calls door. door logs house and pin. house comes from street, its parent. And pin comes from city, its grandparent. So door prints forty two, and three zero two zero zero one. Now door is bundled with street's variables and city's variables. Its backpack has pockets for every level above it, all the way up to global.
Part 4Where are closures used?
Now, why does any of this matter? Because closures are everywhere in real JavaScript. You've probably used them without knowing it. So let's look.
Data privacy, like a counter that nobody can change from outside. The module pattern, where you share some functions but keep variables private. Currying, where a function makes and returns other functions. once and memoize, functions that remember what already happened. And setTimeout and event handlers, which run later, and still remember the values they need. So all of these are closures. Now we'll build some of them in the coming episodes.
And now you can actually see the backpack. In your browser's console, write console.dir, sayHi. Open it up, and look for something called scopes. Inside it, you'll see closure, makeGreeter, and inside that, name equals Riya. So that's the backpack, for real. Try it today, it feels like magic the first time. And here's a secret. You don't even need to return a function to make a closure. Pause inside any inner function while its parent is still running, and you'll see the word closure there too. So every inner function forms one. Returning it just lets us see it in action.
1function outer() {2 var count = 0;3 return function () {4 count = count + 1;5 console.log(count);6 };7}8 9var tick = outer();10tick();11tick();What do the two tick calls print?
Show the answer
So outer runs once, and returns a function with count in its backpack. The first tick adds one, and prints one. The second tick uses the same backpack, the same count, adds one again, and prints two. So one, and then two. If you got that, you've understood closures, and you've just built a tiny counter, all by yourself. Well done!
Where do you think you've already used a closure without knowing it?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.