Reputation: 255
Currently I'm reading JavaScript book. There is a code snippet in it which I can't understand. What's happening in the line repeat(3, function(n) {
? Why we can pass parameter n
to the second argument of the function repeat
, because in its declaration there is nothing about passing parameters? How does repeat
understand that it should pass parameter n
to the unless
function?
function unless(test, then) {
if (!test) then();
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
unless(n % 2, function() {
console.log(n, "is even");
});
});
// → 0 is even
// → 2 is even
Upvotes: 2
Views: 47
Reputation: 35491
Why we can pass parameter n to the second argument of the function repeat, because in its declaration there is nothing about passing parameters
You are not passing n
as the second argument to repeat()
, you are passing an anonymous function that takes a single parameter and you chose to name its parameter n
(so parameter of the function that is passed in)
Functions in JavaScript are, in simple words, just objects that can also be executed. This means you can pass functions around as parameters to other functions, or add properties to them like you would to objects, etc.
Here's an illustration of what is happening in your example:
Function repeat
is defined with two arguments:
repeat(times, body)
So, all you are doing is passing a function
as the body
argument.
Writing it like this is equivalent:
var times = 3;
var body = function(n) {
unless(n % 2, function() {
console.log(n, "is even");
});
};
repeat(time, body);
How does repeat understand that it should pass parameter n to the unless function?
As you can see above, repeat
is not passing anything to unless()
.
It is your anonymous function (stored in body
in my example above) that is actually passing n
to unless
.
Upvotes: 2
Reputation: 4038
If you simply want to write a function to repeat x number of times, and check if it's even, you'd probably want to do it like this:
function repeat(times) {
for (var i = 0; i < times; i++) {
output.innerHTML+= is_even(i)+"\n";
}
}
function is_even(n) {
if ( n % 2 ) return n+" is even";
return n+" is odd";
}
var output = document.getElementById('output');
repeat(6); // Output variable wasn't passed to this function, we're using it globally
<pre id='output'></pre>
Upvotes: 0
Reputation: 245429
You're not passing a parameter n
at all.
In reality, you're passing an entire anonymous function as a parameter (functions are first-class citizens in JavaScript and can be passed around just like other variables).
If you look, the function is passed as the body
parameter to the method repeat
. repeat
then calls the function body
with the parameter of i
...which is the parameter n
in the anonymous function.
Upvotes: 2