bpoinder85
bpoinder85

Reputation: 35

How does JavaScript pass values to a function expression within a declaration?

I'm working through Head First JavaScript and have an example:

 function addN(n) {
        var adder = function(x) {
                        return n + x;
                    };
        return adder;
    }
    
    var add2 = addN(2);
    
    console.log(add2(10));
    console.log(add2(100));

addN(2) gets assigned to add2, but nothing gets assigned to the x. However, upon running the code, the arguments 10 and 100 clearly get passed to the x. How does JavaScript know to pass the 10 and 100 to the x value?

Upvotes: 0

Views: 43

Answers (1)

David
David

Reputation: 219016

When you do this:

var add2 = addN(2);

The variable add2 is now effectively this:

function(x) {
    return 2 + x;
}

Because that function itself is the return value of addN(). (Note that in JavaScript a function is a value that can be assigned to a variable like any other value.)

So when you further do this:

add2(10);

You are passing 10 to that function, so x will be 10.

Upvotes: 2

Related Questions