All 28 lessons ▾
Inside JavaScript · Lesson 12 of 28
A Full Closure Interview, Question by Question
So, closures come up in almost every JavaScript interview. And the questions keep getting harder. So today, let's face that interview together, question by question.
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
- A closure: a function + its lexical environment
- Order, var or let, parameters: none of it breaks it
- It reaches every level; the nearest variable wins
- Uses: data hiding, modules, currying, memoize, timers
- Every call to the outer function makes fresh variables
- The cost: memory, until the closure is gone
Part 1The first question
So imagine you're in a JavaScript interview. You've just said hello, and the interviewer starts with the classic. What is a closure? Now they don't want a memorized line. They want you to explain it with code. So let's do exactly that. Here's the code on their screen.
1function makeTea() {2 var sugar = 2;3 function serve() {4 console.log(sugar);5 }6 return serve;7}8makeTea()();2
So a function makeTea, with a variable sugar, which is two. Inside it, a function serve, that logs sugar. And makeTea returns serve. Now look at the last line. makeTea, and then two pairs of brackets. What's going on? So let's run it. Global is pushed, and phase one stores makeTea. Line eight. The first pair of brackets calls makeTea. Its memory gets sugar and serve. Line two, and sugar becomes two. Line six returns serve, and makeTea is popped. Its box is gone. But we still have one more pair of brackets. The second pair calls serve, right away. Line four logs sugar. And it prints two! Then serve is done too. So makeTea was gone, and serve still printed two. How?
So here's your first answer. Say, a closure is a function, bundled together with its lexical environment. Now when makeTea returned serve, serve didn't travel alone. It carried a reference to makeTea's variables. So even though makeTea's box was deleted, serve still remembers sugar. That's the closure. And then explain the double brackets. The first call returns serve, and the second call runs it. The interviewer nods. Good start! But they're not done with you yet.
Part 2Three quick follow-ups
Now come the follow-ups. Each one changes the code a little, to see if you really understand, or just memorized. So let's take them one by one.
1function makeTea() {2 function serve() {3 console.log(sugar);4 }5 var sugar = 2;6 return serve;7}8makeTea()();So question two. The interviewer moves one line. Now sugar is declared after serve. Is it still a closure? And what does it print? Think. Yes, it's still a closure, and it still prints two. So here's why. serve doesn't take a photo of the variables when it's created. It keeps a reference to makeTea's whole lexical environment. And by the time serve actually runs, line five has already set sugar to two. So the order inside the function doesn't matter.
1function makeTea() {2 let sugar = 2;3 function serve() {4 console.log(sugar);5 }6 return serve;7}8makeTea()();Now question three. What if we change var to let? Will that break the closure? No! It still prints two. let is block scoped, but here the block is the whole function makeTea. And serve is inside that same function. So serve can still see sugar, and the closure works exactly the same way. So a closure doesn't care whether you used var, let, or const.
1function makeTea(milk) {2 let sugar = 2;3 function serve() {4 console.log(sugar, milk);5 }6 return serve;7}8makeTea("oat milk")();Now question four. Now makeTea takes a parameter, milk. And serve logs both sugar and milk. We call makeTea with oat milk, and then call serve. So does serve remember milk too? Yes! A parameter is just a variable in the function's local memory. So it's part of the lexical environment, and it goes into the closure as well. It prints two, oat milk. Simple.
Part 3Going deeper
Now the interviewer smiles, and makes it harder. They wrap everything in one more function.
1function cafe() {2 var city = "Pune";3 function makeTea(milk) {4 let sugar = 2;5 function serve() {6 console.log(sugar, city, milk);7 }8 return serve;9 }10 return makeTea;11}12cafe()("oat milk")();2 Pune oat milk
So question five. Now everything sits inside cafe, which has a city, Pune. cafe returns makeTea, and makeTea returns serve. And serve logs sugar, city, and milk. And observe the last line. Three pairs of brackets! So let's run this one too. Phase one stores cafe. Line twelve. The first pair calls cafe, and its memory gets city, Pune, and makeTea. cafe returns makeTea, and its box is gone. The second pair calls makeTea, with oat milk. Its memory gets milk, sugar, and serve. Then makeTea hands back serve, and that box is gone too. The third pair calls serve. Line six logs sugar, city, and milk. And it prints two, Pune, oat milk! So serve remembered its parent's variables, and its grandparent's city too. A closure keeps the whole chain, all the way up.
1let sugar = 100;2 3function makeTea(milk) {4 let sugar = 2;5 function serve() {6 console.log(sugar, milk);7 }8 return serve;9}10makeTea("oat milk")();Now question six. Now there's a global sugar too, a hundred. And makeTea still has its own sugar, two. So which one does serve print? It prints two. serve looks for sugar using the scope chain. First, its own memory. Nothing there. Then its parent, makeTea. Found it, two! So it stops right there, and never reaches the global hundred. And if makeTea didn't have its own sugar? Then the search goes up, finds the global sugar, and prints a hundred. And if there was no sugar anywhere, you'd get a reference error.
Part 4Why use closures?
Next, the interviewer asks, okay, but why do we even need closures? What are they actually good for?
So give them this list. Data hiding and encapsulation. The module pattern. Currying. Functions like memoize, and once. And setTimeout and event handlers, like in the last episode. Then pick the first one, data hiding, and explain it with an example. Interviewers love this one, so let's build it, step by step.
1var count = 0;2function increment() {3 count++;4}5 6count = -500;So here's a counter, the simple way. A global count, and a function increment. It works. But there's a problem. count is global, so anyone can change it. Any line, anywhere in the program, even another script on the page, can say count equals minus five hundred. And your counter is ruined. So nothing is protecting it.
1function counter() {2 var count = 0;3 function increment() {4 count++;5 }6}7 8console.log(count);ReferenceError: count is not defined
So let's hide it. We move count and increment inside a function, counter. Now line eight tries to log count from outside. And we get an error. count is not defined. Good. Nobody outside can touch count anymore. It's hidden. But wait. Now nobody can use increment either. It's stuck inside too.
1function counter() {2 var count = 0;3 return function () {4 count++;5 console.log(count);6 };7}8var c1 = counter();9c1();10c1();11 12var c2 = counter();13c2();1 2 1
So here's the trick. counter returns the increment function. Phase one stores counter, c1, and c2. Line eight calls counter, and gets back the function, with count in its backpack. Line nine calls c1. count goes up to one, and the console shows one. Line ten calls c1 again. count is two now, so we see two. Now line twelve calls counter again, for c2. That's a brand new call, so c2 gets its own new count, in its own backpack. Line thirteen calls c2, and it prints one. Not three! c1 and c2 don't share anything. And count? Still hidden. The only way to change it is through the function. So that's data hiding, with closures.
1function counter() {2 let count = 0;3 return {4 increment: function () { count++; return count; },5 decrement: function () { count--; return count; },6 };7}8const c = counter();9c.increment();10c.decrement();And now when the interviewer says, now add a decrement too, don't write a second counter. Return an object, with both functions inside it. Both of them close over the same count. So increment and decrement share one private count, and nothing else in your program can reach it. This is the module pattern. You'll also see it written as a constructor function, with the new keyword. We'll understand that properly in the this keyword episodes. Same idea, same closure.
Part 5The one downside
And finally, a question that catches a lot of people. What's the disadvantage of closures?
So here's the answer. Memory. Normally, when a function finishes, its variables can be thrown away. But if a closure still points to them, they have to stay in memory, as long as that closure lives. Create lots of closures and keep them around, and memory keeps piling up. And if you forget about them, that's a memory leak. So closures are powerful, but use them with care.
1function a() {2 var x = 0, z = 10;3 return function b() {4 console.log(x);5 };6}7var y = a();8y();Now who throws away unused memory? The garbage collector. In languages like C, you free memory yourself. In JavaScript, the engine does it for you, automatically. And modern engines like V8 are smart about closures. So look at this. b uses x, but never uses z. So V8 keeps x in b's backpack, and throws z away. Now if you pause inside b in DevTools, and type z, you get an error. z is not defined! It was garbage collected. So the backpack only keeps what the function actually uses.
1function counter() {2 var count = 0;3 return function () {4 count++;5 return count;6 };7}8 9counter()();10counter()();11var c = counter();12c();13console.log(c());What does the last line print?
Show the answer
So lines nine and ten each call counter, and call the new function straight away. Two brand new counts, each goes to one, and both are thrown away. Then c gets its own fresh counter. c is called once, so its count is one. And the last line calls c again, so it prints two. Two! Did you get it? So every call to counter starts a brand new count. Remember this.
Which question was the hardest for you?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.