Posted by : Sudhir Chekuri Saturday, 10 March 2018

A closure in JavaScript is an inner function that has access to its outer function's scope, even after the outer function has returned control. A closure makes the variables of the inner function private. A

Simple example of a closure is shown below:

var count = (function () {
var _counter = 0;
return function () {return _counter += 1;}
})();

count();
count();
count();

// the counter is now 3



The variable count is assigned an outer function. The outer function runs only once, which sets the counter to zero and returns an inner function. The _counter variable can be accessed only by the inner function, which makes it behave like a private variable.


Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -