0

What's the difference between:

// Example 1 sum(8,2)
console.log(sum(8,2));   // Outputs what??
// Example 2 sum(8)(2)
console.log(sum(8)(2));  // Outputs what??

function sum(x,y) {
return x+y;
}

function sum(x) { 
  return function(y){
     return x+y;
     }

}

Why is one used over the other and why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

3

What you are trying to do is called Function Currying

Try this:

function sum(x) { 
   return function(y) { return x + y; } 
}; 
var sumWith4 = sum(4); 
var finalVal = sumWith4(5);
finalVal = sumWith4(8);

One of the advantages is that it helps in reusing abstract function. For example in the above example I can reuse sumWith4 to add 4 to any number with out calling sum(4,5) explicitly. This was a very simple example. There would be scenarios where in part of the function would be evaluated based on the first param and the other part on the second. So you can create a partial function by providing it with the first param and then reuse the partial function repeatedly for multiple different second params.

Community
  • 1
  • 1
MohamedSanaulla
  • 6,112
  • 5
  • 28
  • 45
0

I will be assuming that you mean to ask the difference between the invocation of functions which appear like:-

  1. someFunction(x, y)
  2. someFunction(x)(y)

This happens with the use of Closures which happens to be a concept wherein an inner function can carry the environment in which it was created.

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

var addWith5 = sum(5);
/* 
   This will return a function and not a value
   addWith5 = function(y){return 5+y;}; 
*/
console.log(addWith5(5)); // this will return 11
/*
   You can also use add function directly
*/
console.log(sum(5)(6)); // this will return 11
/* 
   The function returned by sum(5), gets called with the parameter (6)
*/
 //Try using this, to make it more clear
 function a(x){ 
   return x;
 }(5);
 // returns 5

EDIT Removed "closures is a JS concept."

Amresh Venugopal
  • 9,299
  • 5
  • 38
  • 52
  • Closures is not a JS concept. It is a concept in Function Programming. And Javascript happens to have functional programming concepts implemented in it like closures, function currying. – MohamedSanaulla Apr 25 '16 at 05:41