How gets called the inner function?

Tell us what’s happening:
I see in the sample of solutions that there is a second function inside the else if that gets called and receives the param in the second parentesis

-addTogether(5)(7)
-addTogether(2)([3])

given solution:

  if (arguments.length === 2) {
    // Check if we have two arguments and if they are numbers
    // Return the sum if they are both numbers
    let first = arguments[0];
    let second = arguments[1];
    if (checkNum(first) && checkNum(second)) {
      return first + second;
    } else {
      return undefined;
    }
  } else if (arguments.length === 1) {
    // If only one argument was found, return a new function
    let first = arguments[0];
    if (checkNum(first)) {
      // Return function that expect a second argument.
      function addSecond(second) {
        // Check if the new argument is a number
        if (checkNum(second)) {
          return first + second;
        } else {
          return undefined;
        }
      };
      return addSecond;
    } else {
      return undefined;

So, I understand I am not doing exactly the same but I think it is quite the same logic… and it does not work for me, in any case…

the questions are,

  • how does JS knows there is a inner funcion with a different name?
  • how does JS pass the value of the second parentesis to this inner function?
  • why it is not working in mine :frowning:

function addTogether() {
var totalArguments = arguments.length;
if(totalArguments >= 2){
  for(var i=0;i<arguments.length;i++){
    if(typeof arguments[i] == 'number'){
      var result = arguments[0] + arguments[1] 
    }else{
      return undefined;
    }
  }
  return result;
}else if(totalArguments == 1){
  if(typeof arguments[i] == 'number'){
  return function(b2){
    return arguments[0]+ b2;
    }
  }
}
}

console.log(addTogether(2,3));
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36

Challenge: Arguments Optional

Link to the challenge:

Do you mean this?

  if(typeof arguments[i] == 'number') {
    return function(b2) {
      return arguments[0]+ b2;
    }
  }

Does that make sense? Does that answer your question?
That function is not getting called. It is getting defined. It would be the equivalent of:

  if(typeof arguments[i] == 'number') {
    function funcToReturn(b2) {
      return arguments[0]+ b2;
    }
    return funcToReturn;
  }

The point is that it is returning a function, that that it is calling one.

It helped

Thanks a million :wink:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.