The else statement returns a function with the value of x encapsulated from the first call
To explain this, a little break
var fresult = sum(3);
Think about how the value of x will be captured by a return function that you can call
This encapsulation is created by a closure created in an anonymous function in the return else statement.
To learn more about closing, see this MDN article about them , they will be able to explain it much better than I could.
In fact, they have an example that is very similar to yours, where they try to explain the concept as similar to a factory:
function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2));
The article says:
In this example, we defined the function makeAdder (x), which takes a single argument x and returns a new function. The returned function takes one argument y and returns the sum of x and y.
In essence, makeAdder is a factory function - it creates functions that can add a specific value to their argument. In the above example, we use our factory function to create two new functions: adds 5 to our argument and adds 10.
add5 and add10 are both closures. They have the same functional housing but store different environments. In the environment add5 x 5. As for add10, then x is 10.
So, if you are used to a more traditional programming language, some of the use cases that you would use for private variables would be the same as capturing variable values ββin closure
source share