Reputation: 475
I am confused with the scoping of closure expression. I don't understand why output is 40 only.
function multiply(input) {
var no = 5;
function multiply2(mul) {
mul *= input;
return no * mul;
}
return multiply2;
}
var total = multiply(4);
var result = total(2);
console.log("result :",result);
Output
result :40
Upvotes: 0
Views: 72
Reputation: 1267
This is functional programming called currying. An abstract implementation would be y = f(m) => g(n) => m*n
. So your input to f
will be carried into g
and return a function which is g(n)
. Then your input to g
will return the final result.
This can be implemented more than one level. ie. y = f(m)=>g(n)=>h(p)=>m*n*p
, where the input value will be carried to next function until the final input.
Here is some basics of functional programming. Also a great book here.
Upvotes: 0
Reputation: 141829
multiply(4)
returns a function multiply2
which has two free variables in scope: no
which has the value 5
, and input
which has the value 4
. This line assigns that returned function to total
:
var total = multiply(4);
total(2)
calls that function, passing in 2
for the argument mul
. The definition of that function is two statements, but it could be simplified to one statement (since mul
is a local variable and is never used after modifying it, that side-effect can be safely dropped): return no*mul*input;
. mul
was passed in, with the value 2
; no
and input
are the free variables that were created when multiply(4)
was called and we know what they are set to, so, in the statement below, result becomes 5*2*4
, which is 40
.
var result = total(2);
Upvotes: 1
Reputation: 1074
The output 40 is correct. Your functions multiply 4*2 = 8 and then you multiply 8*5 = 40. I think if you aren't getting what you expect is because you are multiplying 4*2 and making mul = 8 so what then gets returned is 5*8
Upvotes: 0