A while ago during a mock technical interview I was asked to explain closures. At first, I thought I knew the answer: "Closures are functions that returns another function". But when I tried to explain it a bit further, I realized that I didn't really understand them. Fortunately my interviewer was very cool about it and went over them briefly with me. Afterwards I went back to basics and read articles, documentation, and watched some Youtube videos to get a better grasp of the topic.
So What Are Closures?
In JavaScript, a closure is the combination of a function and its surrounding scope (lexical environment) within which the function was declared. In fact, a closure is created every time a function is declared. With the help of closures, functions can have local (private) variables that can be accessed even after the parent function was invoked and closed.
Let's take a look at a simple example:
function outer() { // parent function
const message = "Hello"; // local variable
function inner() { // child function
return message;
}
return inner;
}
const greeting = outer();
greeting() // will return a message "Hello"
We have a message variable inside the outer function. It is a local variable and cannot be accessed outside the parent function. By declaring the inner function within the parent function, inner has access to all local variables in its surrounding scope, which in this case is the message variable in outer.
When we assign function outer to the variable greeting, a few things happen:
-
outerfunction runs once and returns child functioninner; -
outerfunction closes itself -
greetingvariable became function declaration, and now has access to the closureinnerand themessagevariable.
Now that greeting function became a function declaration, it can be invoked, and the returned result will be a message from the outer function.
This might seem a bit weird because in some programming languages, local variables within a function only exists for just the duration of the function's execution. But not in JavaScript. In Javascript, functions create closures with all surrounding environment, like variables that are in scope, at the moment they are created.
The greeting function has a reference to the function inner. The latter was created during the outer function execution and holds its environment, in which the variable message exists.
Top comments (1)
Great. Now that you understand the concept, I would like to understand your opinion about its existence. Why do we need closures?