Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript lexical scoping

Tags:

javascript

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));
like image 890
mjmitche Avatar asked Jan 20 '23 10:01

mjmitche


1 Answers

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.

like image 128
meder omuraliev Avatar answered Feb 04 '23 09:02

meder omuraliev