In this article I will explain closure – one of the important concepts in JavaScript. I will also cover the benefits of using closures.
What is a closure?
JavaScript is a function oriented programming language. Because of this we have lots of freedom in using functions. We can easily create a function, pass it as an argument to another function (known as callbacks), define a function inside another function and so on. In JavaScript, the functions which are defined inside another function (i.e. the inner functions) are termed as closures. One important point to note here is closures have access to it’s parent functions scope even after the outer function has returned.
Let’s understand this with an example:
function init() {
var name = 'Lokesh';
// this is a closure
function displayName() {
alert(name);
// using variable declared in the parent function
}
displayName();
}
init();
In the example above, displayName()
function is a closure. As you see, the function has access to it’s parent scope variable name
. So, when the parent function init()
is called, it will display an alert containing the name Lokesh. Although I have shown just one closure in the example, it is absolutely valid to have multiple and nested closures in JavaScript. For example, we can define more functions inside init()
or inside displayName()
too, which is already a closure. You can define as many closures you want.
The main objective behind using closures is data hiding or data privacy. The inner functions (closures) are not exposed to outer world and are not directly accessible from outside scope. The only way to use a closure is by exposing it to it’s parent function. Only parent function can call a closure.
Thank you for reading.
You may also like: What is Callback in JavaScript