Arguments Optional solution question

Arguments Optional solution question
0.0 0

#1

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));

#2

Because that’s the value passed into the [second] function. In the situation you’re describing, the user of the function is calling one function, then another one straight after addTogether(2)(3). Because of closure, the value from the first one is in scope, and the three is added to the two. If you define a variable var g = 100, it doesn’t make any difference; unless you explicitly say that the second function should be whatever the value passed to the first function is + g, it won’t do anything.