You already know that a function has a return statement, which is used to return some value from the function. But what if the return statement returns some other function? Consider the code snippet given below:
function greet(name) { var greeting = "Hi" + name; return function() { console.log(greeting); } } var sayHello = greet("Sakshi");
Now, what will the variable sayHello contain when you try to store the value returned by the function greet()? Let’s look at that in the next video.
Now that you have learned how functions return other functions, let us now look at what closures are in JavaScript.
In the last video, you looked at what closures are and how you can access a variable defined inside the outer function, inside a function closure. A closure is basically an inner function that has access to the outer (enclosing) function’s resources due to the scope chain where a child can access all the resources of its parent. It is basically the combination of a function and the lexical environment in which the function was declared. This closure function has access to all the local variables that were declared inside this lexical scope when the closure function was created.
Now, you know what closures are but wait, what are their applications? Closures are significant in the situations when you require the inner function to access the outer function’s variables (or resources) as long as the inner function wants, even when the outer function has finished executing.
Consider a scenario where you mock the functionality of adding an item to the cart. A simplified code can be considered as the one given below:
function modifyItem() { var items = 0; return { add: function() { console.log("Added item to cart!"); items++; }, getCount: function() { return "Items in cart = " + items; } } } var item = modifyItem(); item.add(); console.log(item.getCount()); // prints 1 item.add(); item.add(); console.log(item.getCount()); // prints 3
Here, the function modifyItem() modifies an item inside the cart. It returns an object consisting of two keys - add and getCount, which contain methods to add an item to the cart and to get the count of the total number of items in the cart.
The value returned by the function modifyItem(), which is an object, is held inside the variable item. On this variable item, the getCount() method is called. Notice that the methods - add() and getCount() are accessible even after the statement modifyItem() is executed meaning that these are accessible even after the function modifyItem() has finished executing.
Thus, you can use the closure function (closure methods - add() and getCount()) even when the outer function (function modifyItem()) in which it was defined has finished its execution and you can still access the resource(s) (items) defined inside the scope of the outer function, in which the closure was created.
You can read more about the practical uses of closures from this link.