When the anonymous function is invoked, why does JavaScript choose the value of 3 to be set to the value of ‘y’? Say we declared a variable inside our addTogether( ) function. We declare, say, var g = 9
at the top inside the addTogether( ) function. When the anonymous function is invoked and JavaScript searches for the value of ‘y’, why does it choose to the value of 3 and not some other value like g = 9
?
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)) {
// console.log('a: '+a, 'b: '+b, 'y: '+y);
return a + y;
} else {
return undefined;
}
};
} else {
return undefined;
}
}
}
console.log(addTogether(4)(3));