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
.