17

C#'s lambda expression also has closures but is rarely discussed by the C# communities or books. I see far more JavaScript people and books talk about its closures than they do in the C# world. Why is that?

Yi Jiang
  • 113
  • 6
TomCaps
  • 311
  • 3
  • 6
  • 3
    Because JavaScript is treated as first class functional language and C# is a classical OOP langauge. Different paradigms, different programming styles. – Raynos Jun 30 '11 at 09:59
  • Please, don't answer stupid thing if you don't know about them. Javascript isn't a functionnal language, not even close. If you are looking for such a language, I suggest you to look at Caml or Haskell for exemple. – deadalnix Jun 30 '11 at 10:32
  • @deadalnix I'm sorry, no-one must have told you JavaScript has first class functions. – Raynos Jun 30 '11 at 10:35
  • 1
    Having first class function does make the language a functionnal language. PHP (since 5.3), python or D has first class function. Would you say that they are functionnal languages ? Certainly not, and javascript either. – deadalnix Jun 30 '11 at 10:46
  • @deadalnix http://www.google.com/search?q=javascript+functionnal – slaphappy Jun 30 '11 at 10:46
  • 1
    @deadalnix JavaScript is a multi-paradigm language. It mainly supports the procedural, functional and prototypical OO paradigm. It's by no means a _pure_ functional language, but you can easily write javascript in the functional paradigm without bending the language. I would say the same of C# and python. – Raynos Jun 30 '11 at 10:50
  • @Raynos Then we agree ;) – deadalnix Jun 30 '11 at 12:09
  • 3
    @deadalnix, a language which allows you to define a Y-combinator is a functional language. By definition. – SK-logic Jun 30 '11 at 13:01
  • Because C# is basically targeted to be an alternative to Java. Wouldn't want to create fear of switching by too strongly promoting powerful features that need a little time to get your head around. – back2dos Jun 30 '11 at 13:18
  • @SK-logic Whith that definition, it would make a language like D or PHP (5.3+) functionnal. This is not what is generally admitted, but why not. – deadalnix Jun 30 '11 at 13:44
  • 1
    @deadalnix: I suppose what it comes down to is the question what approaches are *promoted* by the language. There's many JavaScript frameworks and platforms (notably node.js and DOM (event model)) that rely heavily on first order functions. PHP does have the features that allow for the very same programming style, but if you take a look at the standard API or many frameworks, then you see it's not really at the core of the language. – back2dos Jun 30 '11 at 13:59

6 Answers6

12

Probably because popular implementations of JavaScript's object orientation depend on closures. Let's look at a simple example:

function counter() {
   var value = 0;
   this.getValue = function() { return value; }
   this.increase = function() { value++; }
}

var myCounter = new counter();
console.log(myCounter.getValue());
myCounter.increase();
console.log(myCounter.getValue());

The methods getValue and increase are in fact closures, encapsulating the variable value.

user281377
  • 28,352
  • 5
  • 75
  • 130
  • 3
    -1 "depends on closures" That's highly subjective. It does not. – Raynos Jun 30 '11 at 10:32
  • Raynos: care to show us how to create and use private members without closures? – user281377 Jun 30 '11 at 11:05
  • 1
    @ammoQ there is no such thing as private in JavaScript. What you meant was "because JavaScript classical OO emulation depends on closures". JavaScript OO is prototypical which is a different paradigm. It's a good answer to the question though, "We use closures in JavaScript because there needed to emulate classical OO" – Raynos Jun 30 '11 at 11:33
  • @Raynos: fair enough. Though I think that access control is an important for every OO language, no matter if it's class based or prototype based. – user281377 Jun 30 '11 at 11:43
  • @ammoQ I agree, it can just be done by convention `this._internalTouchItAndItWillBreak` works just fine for me. – Raynos Jun 30 '11 at 11:44
  • Raynos: A programmer will probably follow this convention (thus not access it explicitely), but a for-in-loop would still access the private member and could somehow process it in an unexpected way. – user281377 Jun 30 '11 at 11:53
  • @ammoQ ES5 non-enumerable properties solve that issue. You can also code around it for non-ES5 browsers or use an ES5->ES3 compiler. – Raynos Jun 30 '11 at 11:56
  • @Raynos: depends what you mean with javascript. I you mean the plain language, you're right. But, if you take the libraries one probably uses when using javascript ('the ecosystem'), you will use closures as soon as you do a for loop. Cases in point: JQuery, Prototype, Mootools. – keppla Jun 30 '11 at 12:36
  • @keppla of course closures are useful and powerful. I never stated against that. – Raynos Jun 30 '11 at 12:52
  • my point was not that they are powerful, i was referring to '-1 depends on closures'. It's subjective when referring to the language, but when considering the ecosystem, i would bet, this can be proven statistically ;) – keppla Jun 30 '11 at 13:00
  • 1
    @keppla I meant "OO depends on closures" is subjective. You don't need closures for OO at all. – Raynos Jun 30 '11 at 13:02
  • According to http://en.wikipedia.org/wiki/Object_oriented_programming#features , encapsulation *is* a distinguishing feature of OOP. `this._internalTouchItAndItWillBreak` is not encapsulation. – user281377 Jun 30 '11 at 13:26
  • @ammoQ "A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data." Definition of encapsulation directly from WikiPedia, `this._internal...` is encapsulation. Going any further then this would require setting up a rigorous definition of OO that we both agree on. – Raynos Jun 30 '11 at 13:30
  • Yes, but it also says "A language mechanism for restricting access to some of the object's components." on the same page ;-) BTW, I don't see how a function accesing `this` could be considered bundled with that data. `this` in JavaScript can mean a lot of things, depending on how a function is called, see http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal – user281377 Jun 30 '11 at 14:17
  • @ammoQ `this` is fundamental on context bundling. If you want to inject data into a method you call it with an arbitary context. It's the _very definition_ of data bundling. Again it's completely subjective, I still think your answer is slightly misleading. A small change like "Probably because popular implementations of JavaScripts object orientation depend on closures." will let me remove the downvote. – Raynos Jun 30 '11 at 14:22
  • 2
    you're exposing me as the rep whore I am... – user281377 Jun 30 '11 at 14:44
5

Because javascript doesn't have feature like namespaces, and you can mess up pretty easily with all sort of global objects.

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.

A very common practice for javascript code is writting it like this :

(function(){
    // Some code
})();

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.

Javascript is a very different language than C#. It's not object oriented, it is prototype oriented. This leads to very different practices at the end.

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.

This is usefull to share some data across a set of functions without messing up the global scope. This is the most common use of closure in javascript.

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.

deadalnix
  • 5,973
  • 2
  • 31
  • 27
  • 9
    That's not a closure. You descriping the advantage of using functions to create local scope. – Raynos Jun 30 '11 at 10:00
  • And all function you'll create within will use that local scope, thus, they will be closures. Sorry but your answer show mostly that you are not used to the way javascript works, thus, you should be reading/asking about it more than commenting. For exemple, the code in @ammoQ answer define a function, execute it, and use nested function as closure. Just the same mecanism as explained here. – deadalnix Jun 30 '11 at 10:26
  • 2
    a closure is only a closure if it closes over free variables. Also thank you for telling me I don't know how JavaScript works :) – Raynos Jun 30 '11 at 10:32
  • Yes, you don't. You just explained that javascript was a functionnal language. You just don't seems to know the dufference between a function call in most language and in javascript. Sorry, but that things you tipically heard from javascript's beginners, not specialists. – deadalnix Jun 30 '11 at 10:37
  • 2
    rather then resorting to undermining me by calling me a beginner feel free to put forward actual arguments in the [JavaScript SO Chat room](http://chat.stackoverflow.com/rooms/17/javascript/). This discussion doesn't really belong here, but I'll happily discuss your misconceptions in the SO chat. – Raynos Jun 30 '11 at 10:40
  • 1
    Downvoted. JavaScript is plenty object oriented. It's just not class-based but such functionality is easily authored. It has first class functions, takes advantage of closures to make it a natural fit for heavily event-driven paradigms, and a chief source of inspiration according to its author, Brendan Eich, was Scheme. I'm not really sure what you think a functional language is, but the funny part is that you seem to think class-based inheritance is somehow critical rather than no longer entirely necessary when you can pass functions around and apply them in new contexts. – Erik Reppen Aug 12 '11 at 08:01
  • 2
    -1 as well. This does not describe closures, it describes scope. – Izkata Jul 31 '13 at 17:07
  • @deadalnix It is not necessary to use closures to enclose code in local namespace, you can pass all needed variables as arguments to namespace-function. ps. How function call in JS differs from other languages? – Gill Bates Dec 29 '13 at 07:26
  • This is not the only use of closures. However, JS do not have namespace. As a result, closure are massively used in JS to emulate NS. – deadalnix Jan 06 '14 at 18:39
  • There are no namespace in JS, but its easy enough to declare a named object variable to contain all the properties, values, and functions associated with a particular "purpose". There's no shortage of options for the name to be used for the object. – Craig Hicks Jun 23 '17 at 06:03
4

Because many of the libraries that make JavaScript 'bearable' use them.

Take a look at JQuery, Prototype or MooTools, just to name three popular. Each of those libraries provides an each method for their collections as the preferred way of iteration, that uses an iterator function. That function, when accessing values in the outer scope, will be a closure:

[1,2,3].each(function(item) {
   console.log(item);
});

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.

keppla
  • 5,210
  • 24
  • 32
  • 1
    Why is it not a closure? `console.log` is definied in an outer scope, so `console` is a 'free variable'. And, why is, in effect, a for-loop, which does nothing different, a bad practice? – keppla Jun 30 '11 at 12:56
  • @Raynos: my definition of closure is 'block that contains a free variable', it does not loose that status, it the free variable happens to be on top scope. But, to support my point, consider this method: http://www.pastie.org/2144689 . Why should this be bad? – keppla Jun 30 '11 at 13:06
  • I still think "closing" over global data is considered cheating. I agree that accessing data up the scope chain is fine, it's simply good practice to minimise that access. – Raynos Jun 30 '11 at 13:10
  • Agreed on minimise access – keppla Jun 30 '11 at 13:10
  • It should be noted that with array iterators (forEach, map, reduce, etc) there is zero reason for them to be closures, they have all the state passed into them directly. I would consider it an anti pattern for them to be closures – Raynos Mar 31 '12 at 00:40
  • @Raynos: `zero reason` seems a little hard. For example, `function get_birthdaycount_for(date) { return customers.filter(function(c) { return c.birthday == date }).length() }` does not seem particularly evil to me. – keppla Apr 02 '12 at 08:50
  • https://gist.github.com/c763d704e1b4e5555673 Notice how your not creating a new filter function pointlessly every time you invoke `get_birthdaycount_for`, closures are expensive – Raynos Apr 02 '12 at 12:44
  • When the performance impact is not too great, i would prefer the anonymous variant. could you recomend some places where i could educate myself on the expensiveness? – keppla Apr 02 '12 at 14:53
  • Your creating a new function every time you invoke `get_birthdaycount_for` for no reason other then "personal preference". Function creation has non zero cost. Write a jsperf if you want to see the actual difference – Raynos Apr 02 '12 at 17:08
3

I agree with the other answers that "good" coding with JavaScript is more heavily dependent on closures. However, in addition to that, it is probably just a question of how long the feature has been around in each language. JavaScript has basically had closures since its earliest implementations. C# on the other hand has only had them since 3.0, which was released with Visual Studio 2008.

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.

RationalGeek
  • 10,077
  • 7
  • 38
  • 56
2

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.

In JavaScript, on the other hand, closures enable functions to behave as methods when accessed as an object property and being first-class objects, they can also be injected into different environments which allows subroutines to operate in different contexts.

Filip Dupanović
  • 1,215
  • 8
  • 13
  • 1
    What does static typing have to do with this? Closures are orthogonal. –  Jul 31 '13 at 14:49
-1

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: https://stackoverflow.com/questions/5606059/how-to-create-closure-in-loop-and-store-it-in-variable-for-later-execution

Trevor
  • 1,501
  • 1
  • 13
  • 15