Arguments Optional 'addTogether is not a function'

Hi, so from reading around the forum I’m supposed to return a function if there is more than one set of arguments passed, like in the example addTogether(2)(3)

I’m trying to take a look at this and understand what’s going on, but everything I do just returns ‘is not a function’. I don’t have working code, at the moment I’m just trying to access the second set or arguments, or gets arguments length. I don’t understand what’s going on or how to access the 3!?

If addTogether(2) returns a function you can access the other parameter

As in

let addTwo = addTogether(2);
let result = addTwo(3);

addTwo hold the function returned, and writing addTwo(3) you are passing the argument inside that function

You can avoid the extra variable just writing addTogether(2)(3) as that is equal to addTwo(3)

If addTogether doesn’t return a function, you will get the error because then you are trying to pass the 3 to something that is not a function

1 Like

It’s called Currying:

function add(a) {
  return function(b) {
    return a + b
  };
}

// const add = a => b => a + b;

add(2)(3); // 5
1 Like

Thank you, so that’s what this bit refers to:

"Calling this returned function with a single argument will then return the sum:

var sumTwoAnd = addTogether(2);

sumTwoAnd(3) returns 5 ."

I was wondering where the sumTwoAnd came from, but that’s supposed to be the function that’s returned and you can have it anonymous if you like?

Anonymous as in writing addTogether(2)(3)? Sure. You can do with it whatever you usually do with functions

So to access the subsets I can just keep going deeper and deeper? Is there anyway to determine within the function how many subsets are being passed?

function addTogether() {
  
var getNum = function(num) {
     num = function(num) {
        return num
      }
      return num
  };

return getNum

}

addTogether(2)(3)(5);

This is a recursive function, the function is calling itself from inside the function. Don’t do that f you don’t know how to work with the recursiveness, and with a condition to stop it, you will just end with a stack overflow

Okay thanks but when I ran this code it returned the 5 which is what I thought it would do when I wrote it…

So just to check the logic, I thought at first these were two arguments being passed in different syntax, but actually (2) needs to be made into a function that can then take (3) as an argument?

Oh, you are right, you just used the same name for the function and its parameter. It can become incredibly confusing. Please avoid, you want to be sure what is what.

(2) is not a function by itself. When you write functionName(2) and that returns a function, you can write functionName(2)(3)

Try checking this if it helps you inderstand: