Click here to Skip to main content
15,915,094 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Why this code outputs 8? I can't fully understand it. Can someone describe me, what is going on in code?

Code:

function outer(a) {

function inner(b) {
return a + b;
}
return inner;
}

var f = outer(3);
f(5);

//ouput: 8

What I have tried:

I was trying to guess it, but actually I can't get to know, why is ouput 8. In the first is set parameter 3 for outer (a = 3). So
function inner(b) {
return 3 + b;
},
but after that we set parameter a for function outer to 5, so function inner(b) {
return 5 + b;
} ?
No, I really can't understand what is going on in code.

Btw I'm really young student.
Posted
Updated 30-Aug-18 2:09am
Comments
ZurdoDev 30-Aug-18 8:16am    
Step 0: Learn to debug. All your questions shall be answered. See Solution 1.
Richard Deeming 30-Aug-18 9:39am    
This is commonly known as "partial application":
Ben Alman » Partial Application in JavaScript[^]

In general, the technique of capturing state from an outer function is known as a "closure":
Closures - JavaScript | MDN[^]

1 solution

Javascript... reading that code got me thinking how it works as well..
I added console.log and see how the control flows:
JavaScript
function outer(a) {
console.log('outer: ' + a)
function inner(b) {
  console.log('inner:' + b);
  console.log('inner:' + a);
return a + b;
}
  console.log(inner);
return inner;
  
}


var f = outer(3);

Output:
"outer: 3"
-----------------------------------------------------
function inner(b) {
window.runnerWindow.proxyConsole.log('inner:' + b);
window.runnerWindow.proxyConsole.log('inner:' + a);
return a + b;
}
-----------------------------------------------------



f(5);

"inner:5"
-----------------------------------------------------
"inner:3"
-----------------------------------------------------
8
-----------------------------------------------------


The first call
var f = outer(3);
sets variable "a" to 3, then outer function returns "inner" function definition.
Then 2nd call
f(5)
it calls the "inner" function, and assigning variable b = 5. In Javascript closure, variable "a" retain its value "3". So 5 + 3 = 8.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900