First of all, the way the function is being called throws me off. How can a function be called with two separate parens like the one in this example?
addTogether(4)(3)
Lastly, could someone please explain how the closure works in this if statement(please see full code below)?
if(a) {
return function(y) {
if(checkIfNum(y)) {
return a + y;
} else {
return undefined;
}
};
If we call addTogether()
like this:
addTogether(4)(3)
, I understand that argument a
is set to 4
but not sure how y
is set to 3
.
function addTogether() {
function checkIfNum(num) {
return typeof num === 'number' ? num : undefined;
}
var a = checkIfNum(arguments[0]);
var b = checkIfNum(arguments[1]);//if there is no second argument, var b = undefined;
if(arguments.length > 1) {
return a && b ? a + b : undefined;
} else {
if(a) {
return function(y) {
if(checkIfNum(y)) {
return a + y;
} else {
return undefined;
}
};
} else {
return undefined;
}
}
}
console.log(addTogether(4)(3));//7
On the first invocation, addTogether(4), 'var a = checkIfNum(arguments[0]);' resolves to 'var a = 4'. The first invocation of addTogether() causes our anonymous function (y) to be invoked and returned to the main function addTogether(). When anonymous function (y) is invoked, JavaScript searches for the value of 'y'. How does JavaScript decide that '3' will be the value of 'y'? My guess is that on the first invocation of addTogether() or addTogether(4), the argument object associated with addTogether() is set to the value of 4. Once 4 gets passed to the function addTogether(), we now have 'a' = 4 trapped in the closure created by addTogether() and at the same time, essentially we have three things happening : #1 : 'a' = 4, # 2 : the argument of addTogether() is now set to the value of 3 or addTogether(3), #3 : anonymous function (y) is returned and invoked causing JavaScript to search for the value of 'y'. JavaScript sees that at this exact point in time, the argument of addTogether() is set to the value of 3 so JavaScript sets the value of 'y' to 3. How does JavaScript know to set 'y' to the value of 3? When a function is invoked inside another function, does JavaScript automatically set the value of the argument of the, for lack of better words, "child" function to the value of the argument of the "parent" function? Is there something about the arguments object that I'm missing here?