Home > OS >  Two parenthesis while calling a function calls in javascript
Two parenthesis while calling a function calls in javascript

Time:07-30

function abc(){ console.log()

}

abc(5)(2)

I need to get output as 10. Please explain it.

CodePudding user response:

/* You need to use concept of closures to achieve this */


function abc(x) {
  return function (y) {
    return x   y
  }
}

console.log(abc(5)(10))

CodePudding user response:

First parameter will execute the outer function, the second parameter will be execute the returned function the inner function

// x is the first parentheses will equal 5
function abc(x) {
   // y is the second parentheses will be equal 2
   return function(y) {
       return x * y
   }
}

console.log(abc(5)(2))

CodePudding user response:

If I understood correctly your question you want some explanation of how and why you ever want to write a function with two separated arguments like that.

I add some example using arrow function (es5 syntax is a bit longer and confusing)

//basic multiply function
const multiplyBasic = (a, b) => a * b

//curried multiply function
const multiply = a => b => a * b


console.log(multiply(2)(5))


// you can also define a series of functions based on the curried version

const double = multiply(2)
const triple = multiply(3)

//usage 

console.log(double(5), [1, 2, 3].map(double))

  • Related