-1

I am working in javaScript from last 3 months, but not able to understand something about closures :

  1. What problem exactly closure resolved in this language ?
  2. When should I use closure ?
  3. Is it related to performance or only case of best practice ?

I read How do JavaScript closures work? , which have pretty good explanation but I am not able to get answes of above questions.

Community
  • 1
  • 1
Anshul
  • 9,312
  • 11
  • 57
  • 74
  • 1
    Closure mostly avoid to use variable in global scope. e.g, when using different plugins, if each plugin use same name variable in global scope, the last loaded plugin will override the previous variable of the other plugin. Closure let you keep value of variable too especially if you are doing some async operations inside a loop. – A. Wolff Jun 27 '13 at 11:14
  • This article might help you out. http://msdn.microsoft.com/en-us/magazine/ff696765.aspx Just keep googling and reading, there are tons of articles out there – Geoff Jun 27 '13 at 11:16

1 Answers1

2

Here is a closure example:

var items = ["a","b", "c"];
var displayItem = function (i) {
    return function () {
        alert(items[i]);
    }
}

for (var i = 0; i < items.length; i++) {
    window.setTimeout(displayItem(i), 100);
}
  1. A closure keeps the context information of a function. In this example the closure keeps the number if the counter and the items array. If I wouldn't use the closure the conter would have changed and all alerts would show undefined (var i whould be 3).

  2. You are using closures and you may have not noticed. There are no rules of when to use them. When declaring functions inside other functions you are creating closures. In this example I created a closure with just the data I needed. But the displayItem function has created a closure that allows him to acces to the items array.

  3. Using closures may have performance issues because you're forcing the browser to keep more data in memory. So people doesn't use it for performance and nor as a best practice, it is simply an other tool to solve some problems.

Kaizo
  • 4,155
  • 2
  • 23
  • 26