-1

Now I have to solve a exercise in the exercise from freecodecamp. The outcome are expected as follows:

addTogether(2, 3) should return 5.

addTogether(2)(3) should return 5.

addTogether("This is sth") should return undefined.

addTogether(2, "3") should return undefined.

addTogether(2)([3]) should return undefined.

And by referring to some suggested solutions, one of the solutions is like:

function add(){
   var args= [].slice.call(arguments);

   if (!args.every(function(argument){return typeof argument === 'number';})){
    return undefined;
   }

   if(args.length === 2){
    return args[0] + args[1]; 
   } else {
    var a = args[0];
    var addOne = function(b){
      return add(a,b);
    };
    return addOne; 
   }
  return false 
}

add(2)(3)

In here, I am not really sure, why in the variable addOne, the anonymous function will successfully capture the the value in the second brackets, after calling the first value before?

I seek for the information about JavaScript function invocation, but still do not 100% sure why...

Edited: With the features of closure, because I have already extracted the first parentheses, the next closure i.e the function, will automatically take the second input? And in this case, if I want to do addTogether(2)(3)(4)(5) , then I can do that by creating closures within different parentheses e.g

 var a = args[0];
  var addOne = function(b){
    var addTwo = function(c){
     var addThree = function(d){
       return a+b+c+d;
     }
   }      
};

Do I understand in the correct sense?

Pak Hang Leung
  • 389
  • 5
  • 15

1 Answers1

1

In here, I am not really sure, why in the variable addOne, the anonymous function will successfully capture the the value in the second brackets, after calling the first value before?

Because, when you say, addTogether(2), it means you're calling a function and passing it an integer 2, and when you say addTogether(2)(3), it means, you're calling a function and passing it an integer 2, which is then returning a function, to which you're passing the integer 3.

So, when the code says return addOne, it is returning the function which is called with the second parentheses, (3), so addTogether gets the value 2 and the return of addTogether, which is addOne gets the value 3.

rmn
  • 1,119
  • 7
  • 18
  • Many thanks! That means, with the features of closure, because I have already extracted the first parentheses, the next closure i.e the function, will automatically take the second input? And in this case, if I want to do addTogether(2)(3)(4)(5) , then I can do that by creating closures within different parentheses? – Pak Hang Leung Sep 11 '18 at 06:20
  • @PakHangLeung Thats true. Although it is not a good pattern to follow, but for research and learning, this is great. – rmn Sep 11 '18 at 06:57