- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
So it is important to be able to isolate some code in its own execution environment. Closure are perfect for that.
This usage of closure doesn't make sense in a language like C# where you have namespaces, classes and so on to isolates code and not putting everything in the global scope.
As you can see, this is an anonymous function declaration, followed immediately by its execution. Thus, everything defined within the function is impossible to access from outside, and you will not mess up the global scope. The execution context of this function will remain alive as long as some code uses it, like nested functions defined within this context, that you can pass as callback or whatever.
Anyway, closures are good, so use them, even in C#!
EDIT: After some discuss on stackoverflow's chat, I think this anwer has to be precised.
The function in the sample code isn't a closure. However, this fucntion can define local variable and nested functions. All nested functions that use these local variables are closures.
Closure are way more powerfull than just sharing some data like this, but let's be realistic, most programmers don't know a thing about functionnal programming. In C# you would have used class or a namespace for these kind of use, but JS does not provide this functionnality.
You can do way more with closure than just protect the global scope, but this is what you'll see in JS source code.
A lot of C# programmers I run into are still working on 2.0 projects. And even if they are working in 3.0 or 4.0, they often are still using 2.0 idioms. I love closures; hopefully they will become more heavily used in C# as the concept propagates among C# developers.
Take a look at JQuery, Prototype or MooTools, just to name three popular. Each of those libraries provides an
And it does not stop there: Callbacks in Ajax, event handling in Ext.js, etc all take functions, and if you dont want to bloat your code with 100eds of functions that are called exactly once, closures are the way to go.
The main reason is because C# is statically typed and functions only have access to a single, predetermined environment, which impedes the usefulness of closures.
One reason I had to learn about them was because when you're looping through DOM elements (or anything really), you want to be able to "close" or "encapsulate" the variable scope. As in the example posted here: http://stackoverflow.com/questions/5606059/how-to-create-closure-in-loop-and-store-it-in-variable-for-later-execution