Hi, can anyone explain how this function would work? I understand by format it is a self-invoking function but I don’t know how it would work in case of arguments.
addTogether(2)(3); //should return 5.
Hi, can anyone explain how this function would work? I understand by format it is a self-invoking function but I don’t know how it would work in case of arguments.
addTogether(2)(3); //should return 5.
What you wrote is this
let fn2 = () => return some_value
let fn = () => fn2
Suppose you call fn
fn() // this returns fn2, if you call it again you are making a call to fn2
fn()() // This is calling fn2
This is actually a curried function, not a chained function.
A curried function is a function that returns another function. But it won’t return a result until all arguments have been passed in.
So addTogether(2)(3)
would look like this
function addTogether(firstNum) {
return function(secNum) {
return firstNum + secNum
}
}
// arrow function makes it clearer
const addTogether = (firstNum) => (secNum) => firstNum + secNum
So what happens is when you call addTogether
with one argument you actually get this
const add2 = addTogether(2)
console.log(add2) // function(secNum) { return firstNum + secNum }
Because of closures, the firstNum
parameter is still available to the second function, even after the first function returns.
And since you’re returning a function, you then have to call that function with it’s second argument
/*
* the variable add2 stores the result of passing in
* the first argument of 2.
*/
add2(3) // 5
This is a very powerful functional programming pattern, because you can store partial functions if you know beforehand the structure of your data.
const add10 = addTogether(10)
const add5 = addTogether(5)
/* ...etc */
Resources:
Thank you all for the help and making it clear