Self invoking function

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.

It is a chained function not self-invoking.

If written correctly, addTogether will take the value 2 and return a function which will add the value 2 to the value inside the second parentheses and return the sum. Think of it as two functions executing in a series. The (3) is just the call on the function which is returned.

1 Like

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
1 Like

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 */


1 Like

Thank you all for the help and making it clear :+1::slightly_smiling_face: