JavaScript closures are one of those things that the vast majority of JavaScript developers use on a daily basis, but when faced with the popular interview question of “What is a closure?”, would stare wide-eyed back at the interviewer with absolutely no idea what to say.
This is an odd thing. Not least because on paper, the answer is incredibly simple: A closure is a function with access to the variables in its enclosing scope.
Time for a simple, and not particularly useful, example.
In this example, we have a function makeAdder()
which creates and returns a function that adds any number of your choosing, to another number. Think of this like a function “factory”, you tell it “I want to add the number 7 to things”, and it gives you add7()
, then when you call add7(4)
, you get 11.
The reason this is a closure is because the inner function returned by makeAdder()
closes around the amountToAdd
parameter in the parent scope, which will then never change. However, this isn’t a particularly useful example, so let’s take a look at a more practical one:
In this example, we use a closure to not only store a running balance for each instance of wallet, but also to secure the variable as private. No script on the page can manually change the balance by running wallet1.balance = 1000
(look in the code, I tried!), so all scripts must go through the normal process of calling alterBalance
, which of course then means that normal processing can be done on the request.
The funny thing about closures is that in JavaScript, they are everywhere. If you really think about its core definition (“A closure is a function with access to the variables in its enclosing scope”), and then go hunting through your code, I’m fairly certain you’ll fine one.
So, next time you have a technical interview and they ask this question, don’t panic! It’s not some fancy ES6 function, or a long-forgotten side-effect of a deprecated object type. It’s a concept, and a common one at that.
Top comments (0)