Javascript Lexing Area

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

what happens to returning an internal function? i m assuming that the enclosing function return is assigned to the variables addTwo and addFive... where does the inner function get its argument (number)? I Im completely lost on this, and the textbook does not 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)); 
+4
source share
2 answers
 var addTwo = makeAddFunction(2); 

1 . 2 assigned as amount and attached to the scope of the function. The add internal function has access to this, and therefore keeps it โ€œcachedโ€.

So, that returns essentially function(number) { number + 2 };


 var addFive = makeAddFunction(5); 

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

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

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

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

5. 6 and 3 , so we get 9 .

6 . 9 is passed to the show function.

+7
source

makeAddFunction returns an add function that adds a quantity to a quantity.

on the line var addTwo = makeAddFunction(2); you created a function with amount 2. If you call this function ( addTwo ) with some number, it returns 2 + passed argument

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

addFive(1) = 5 + 1 = 6

6 + 3 = 9

+2
source

Source: https://habr.com/ru/post/1340741/


All Articles