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?

3
  • one is a function and the other gives: Uncaught SyntaxError: Unexpected token ( Commented Apr 25, 2016 at 5:29
  • 1
    Uncaught SyntaxError: Unexpected token ? Difference: Second one will produce an error whereas first one will execute as expected :) Commented Apr 25, 2016 at 5:29
  • What you are trying to do is called Function Currying Commented Apr 25, 2016 at 5:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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."

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.