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?