texi rv texi rv - 2 years ago 157
Javascript Question

difference between js functions by using parameters

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)(y) {
return x+y;


Why is one used over the other?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download