How can I make var a = add(2)(3); //5 work?

rajakvk picture rajakvk · Feb 16, 2010 · Viewed 61.9k times · Source

I want to make this syntax possible:

var a = add(2)(3); //5

based on what I read at http://dmitry.baranovskiy.com/post/31797647

I've got no clue how to make it possible.

Answer

tvanfosson picture tvanfosson · Feb 16, 2010

You need add to be a function that takes an argument and returns a function that takes an argument that adds the argument to add and itself.

var add = function(x) {
    return function(y) { return x + y; };
}