I was in an interview and I got all the questions right except for this one.
The first question leading up to it was how do you write a function for mod(3,9)
so that it returns 0.
Ok, easy:
function mod(a,b){
return b%a;
}
After that was how do you write the function mod(3)(9)
so that it returns 0?
I was stumped...
You write a function that returns a closure.
function mod(a) {
return function(b) {
return b % a;
}
}
alert(mod(3)(9));
The alert
expression is short for:
var tempfun = mod(3);
alert(tempfun(9));
When you call mod(3)
, it returns a function that takes an argument b
, and performs the modulus with the saved binding of a
, which contains 3
. We can then use that in the same way we'd use any other function: we can assign it to a variable and then call that as a function, or we can just call it directly by putting another pair of parentheses after it.
First of all, look closely at the usage of this construction:
mod(3)(9);
You can split it into two steps:
var fn = mod(3);
fn(9);
From here is it obvious that mod(3)
alone must return a new function so that later it could be invoked again. This new function needs to preserve the value passed in with the first invocation. This is the key part: you should store that value in the closure (well it's stored automatically due to nature of closures):
function mod(x) {
return function(y) {
return y % x;
};
}
Here comes good illustration of the term "closure". If someone asks you (on interview, for example) you may say: closure is the function with the scope it was originally created in. So in the function above, new inner function always has internal access to the outer function parameter x
.
You can use a function that returns another function
function mod(a) {
return function(b) {
return b % a;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With