4

I have used JS for two years and my pluralsight accessment rates me as proficient in JS, I understand prototypical inheritance, higher order functions, IIFEs etc and I have used them in real world instances but closures is one of those concept that you understand but can't find any reason why you would want to use them in real world development, I mean I know that if I say,

function expClosure(val){
   //do something to val-->anotherVal
   return function(val){return anotherVal)};
}
var exp = expClosure(val);
exp(); --> returns the value of anotherVal;

My question is why would I want to do this, or rather what specific instances can lead me to consider using this.

  • it should be `return function(otherVal){return anotherVal)};`, because you overwrite the closure with the use of `val`. now it is a closure over `val`. – Nina Scholz Mar 25 '17 at 11:35
  • Closures are used very frequently in callbacks, so they can retain the values of variables that were bound when the asynchronous function was called. – Barmar Mar 25 '17 at 11:51
  • I suspect your real curiosity is about higher-order functions, not about closures in general. – Barmar Mar 25 '17 at 11:52
  • Adding a demo jsfiddle here https://jsfiddle.net/guptaaditya24/2qveyn0w/ – Aditya Mar 25 '17 at 12:16
  • A related post [here](https://stackoverflow.com/q/2728278/465053). – RBT Oct 09 '17 at 00:36

3 Answers3

1

The main benefit to closures is you can "partially apply" a function using a closure, then pass the partially applied function around, instead of needing to pass the non-applied function, and any data you'll need to call it (very useful, in many scenarios).

Say you have a function f that will need in the future 2 pieces of data to operate. One approach is you could pass both pieces in as arguments when you call it. The problem with this approach is if the first piece of data is available immediately, and the second isn't, you'll have to pass it around with f so it's in scope when you want to call the function.

The other option is to give the available data to the function immediately. You can create a closure over the data, have the function reference the external data, then pass the function around by itself.

Option 2 is much simpler.

You can also use closures to implement static variables in functions in languages that don't natively support them. Clojure (the language) implements it's memoize function by having it return a modified version of the passed function that holds a reference to a map representing argument/return value pairs. Before the function is run, it first checks if the arguments already exist in the map. If they do, it returns the cached return value instead of recalculating it.

(Adapted from my answer to another question)

Community
  • 1
  • 1
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
1

I wrote a bit about this in my practical bachelor thesis(2.2.2)

Hiding variables is a valuable usage of closure. Compared to some other languages variables can't be declared as private, public, etc. in JavaScript, but using closure you can hide variables that can only be used internally. E.g.

function Car() {
   var speed = 0;

   return {
      accelerate: function() {
         speed++;
      }
   }
}

var car = new Car();
car.accelerate();

speed is accessible by accelerate due to closure, but is otherwise completely inaccessible.

MyiEye
  • 445
  • 1
  • 4
  • 14
0

Since this question doesn't demand a programmatic answer, I am adding an answer and not a comment. The example you quoted in the question is, I agree of a closure, and I am sure having access to pluralsight lectures, you well understand closures. So the aforestated example is not the only use case of closures. The closures are the functions which remember the scope in which they were created.

An obvious example of this is a callback registering mechanism which every one uses in jQuery. There are closures everywhere, and many of us have been unknowingly writing closures.

So if you have used redux, you would know the entire concept is based on closure, i.e. encapsulating the data(called state of application). Closure provisions a concept of private variables used in OOPS supporting languages.

I am adding another example of closure below, so you might be able to relate.

function processOrder(amount){
  var temp_order_id = +new Date() + 'USERID';
  var afterPaymentCompleteOrder = function(status){//callback
  //afterPaymentCompleteOrder is a closure as it remembers the scope in which it is created when it is being called. So when ivoked it remembers the value of temp_order_id
     if(status){
          complete_order_method(temp_order_id);
     }
     else
          delete_order_details(temp_order_id);
  }

  start_payment_process(amount, afterPaymentCompleteOrder);
}
Aditya
  • 861
  • 5
  • 8