mjmitche
mjmitche

Reputation: 2067

Javascript lexical scoping

Can someone please explain in plain language how this code works to give a result of 9?

what happens to the return of the inner function? Im assuming that the enclosing function return is assigned to the variables addTwo and addFive... where does the inner function get its argument (number)? Im totally lost on this and the tutorial doesn`t explain it.

function makeAddFunction(amount) {
  function add(number) {
    return number + amount;
  }
  return add;
}

var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));

Upvotes: 4

Views: 939

Answers (2)

meder omuraliev
meder omuraliev

Reputation: 186552

var addTwo = makeAddFunction(2);

1. 2 is assigned as amount and bound within the function scope. The inner add function has access to this, and so keeps it "cached".

So what is returned is essentially function(number) { number + 2 };


var addFive = makeAddFunction(5);

2. 5 is assigned the same way, and function(number) { number + 5 }; is returned.

show(addTwo(1) + addFive(1));

3. function( number ) {number+2} is invoked and 1 is fed to the function, so 2+1 is returned which is 3.

4. function( number ){number+5} is invoked and 5 is fed to the function, so 5+1 is returned which is 6.

5. 6 and 3 are added, so we get 9.

6. 9 is fed to the show function.

Upvotes: 7

Sergey Vedernikov
Sergey Vedernikov

Reputation: 7754

makeAddFunction returns function add that adds number to amount.

in line var addTwo = makeAddFunction(2); you've created a function with amount 2. If you call that function(addTwo) with some number, it return 2 + passed argument

By this logic: addTwo(1) = 2 + 1 = 3,

addFive(1) = 5 + 1 = 6

6 + 3 = 9

Upvotes: 2

Related Questions