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.
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.