Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Contact us
Hide Buttons

Closures, Currying, Partially applied functions in javascript demystified

We need to understand closures first before we understand currying.

closures allows inner function to access the variables in the outside function in which it is declared. Below MDN example explains it very well.

function init() {
  var name = 'Mozilla'; // name is a local variable created by init

  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();

currying a.k.a. partially applied function

In javascript, function can return a function. Because of that we can call the returned function with variety of arguments. For example,
– we can pass arguments as usual we do to all the functions
– we can use variables from its parent function where it the function was declared via closure
– we can partially process the arguments before passing it to the returned function via closure
– we can prefix these arguments with some value and so forth

So, this idea of calling the return function with variety of arguments is called currying.

For example, write a function sum which can accept both the syntax.

sum(5, 3) // 8
sum(5)(3) // 8

Logic

  • Whenever the sum is called we need to detect if its called with two arguments of one.
  • If its called with two arguments then the problem is very simple
  • Else the sum function returns another function which has accepts one argument and it has access to the variable a via closure.

Solution

More examples

Reference


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *