15,790,267 members
See more:
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 3:09am
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[^]

## Solution 1

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.

v3