3

What are the benefits of using closures in JavaScript and why should I consider them in my code if I can usually write a more simple and straightforward solution, at least in my opinion.

For example, consider this:

    function multiplier(factor) {
       return function(number) {
          return number * factor;
       };
    }

    var twice = multiplier(2);
    console.log(twice(5));

//////////////////////////////////////////////////////////////////

    function myMultiplier(factor, number) {
         return number * factor;
     }

    console.log(myMultiplier(2, 5)); 

They both output 10, but I find myMultipler easier to understand, quicker to write, and I only needed one function to do it. Why should I consider the closure version over my-version?

Thanks in advance.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
DEdesigns57
  • 361
  • 1
  • 5
  • 13
  • In this particular case, there's no reason. – Linuxios Aug 30 '14 at 15:00
  • http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 – worldask Aug 30 '14 at 15:02
  • 1
    No, you don't need a flamethrower to light a cigarette. – jimm101 Aug 30 '14 at 15:04
  • Imagine that at t0 you only know the factor and at t1 you only know the number. It's the only use case I can think of right now – axelduch Aug 30 '14 at 15:05
  • partial function application is one reason why you would consider closures. Just like in your example. – akonsu Aug 30 '14 at 15:07
  • 2
    In your example closures are not useful. Closures allow persistent variables that do not pollute the global name space. You can call a function multiple times and it will 'remember' what was there before. – Steve Wellens Aug 30 '14 at 15:09

3 Answers3

3

One of the typical scenarios in which you might need a closure are for loops that register event handlers. A for loop does not create a new scope. That means if within the loop you're registering an event handler that relies on the values of local variables during the loop pass, you'll need a closure to wrap the values with the handler.

Consider the following two snippets. The one without the closure will lead to unexpected results.

Without Closure

for(var i = 0; i < locations.length; i++){
    var marker = new google.maps.Marker(...);
    ...
    google.maps.event.addListener(marker, 'click', function(){
        ...
        // At the time of click the for loop has finished.
        // Thus, marker will be the last marker that was created in the loop.
    });
}

With Closure

for(var i = 0; i < locations.length; i++){
    var marker = new google.maps.Marker(...);
    ...
    google.maps.event.addListener(marker, 'click', (function(marker){
        return function() {
            ...
            // The marker object is wrapped in the closure and
            // will possess the correct value
        }
    })(marker)); // Pass in marker to make the closure work
}
hennes
  • 9,147
  • 4
  • 43
  • 63
2

The code in your question only demonstrates 'what a closure is' and is equivalent to writing a 'hello world' application.

Closures allow you to pass not only data around, but also logic. This increases the reusability of some parts of code:

var arr = [81,55,75,5,3,6,95,0,55,-97];

var sorter = function(modifier) {
    return function(arr){
        arr.sort(modifier);
    };
};

var asc = sorter(function(a,b){
   return a > b; 
});

var desc = sorter(function(a,b){
   return a < b; 
});

asc(arr);
console.log(arr);

desc(arr);
console.log(arr);

This outputs:

[-97, 0, 3, 5, 6, 55, 55, 75, 81, 95]
[95, 81, 75, 55, 55, 6, 5, 3, 0, -97] 

See: http://jsfiddle.net/jimschubert/7nnycrfj/

edit: You can see how reusability works by adding arrays of different types: http://jsfiddle.net/jimschubert/7nnycrfj/1/

Joseph Yaduvanshi
  • 20,241
  • 5
  • 61
  • 69
-3

If you can write a more simple and straightforward solution, do it that way. Talking javascript or talking whatever.

That the feature is there does not mean you should use it. You should use it if it serves to your purpose. You should not use closures in this case, as you point.

BUT Closures are not useless at all. They are a main feature on many programming languages. You can look at any docs about them to get what they are useful for. Here for example.

RubenCaro
  • 1,419
  • 14
  • 12