in EJ section lesson of Abstracting repetition. they show 2 code example that I just don’t quite understand, especially when I tried to run the code in other place, it just didn’t work the way it supposed to be…
the first code:
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, console.log);
// → 0
// → 1
// → 2
my question in this code might sound dumb, but I don’t get what is the value of action(i)? why parentheses is used here?
JavaScript can use functions as values. (Wait what? I know, just keep reading.)
In this case the parameter “action” gets “console.log” as function value and is invoked inside the loop which technically becomes.
function repeat(n, action=console.log) {. // Here action becomes console.log
for (let i = 0; i < n; i++) {
console.log(i);
}
}
The parentheses are used to invoke the function which was only a passed value until then.
The second case is about the same.
This time around this function is passed as value
then (note pushStuff) is now what “action” parameter becomes, but just another function as value
repeat(5, pushStuff);
Should do just the same.
Keep in mind : “In JavaScript, functions are not only syntax but also values, which means they can be assigned to variables, stored in the properties of objects or the elements of arrays, passed as arguments to functions, and so on.”
Hope this helps.
Comments:
I love Eloquent JS webpage.
You are learning fast, I’ve seen your other questions, great stuff. Keep going.
thanks for explaining! I just realized that the code for action(i), is calling for the console.log(i).
but for the second code i still couldn’t wrap my head around it, precisely in this part
repeat(5, i => {
labels.push(`Unit ${i + 1}`);
});
i understand that it’s taking a function to passed as value, but what i don’t understand is that, what make the code iterates the number?
because my understanding is that, this code:
i => {
labels.push(`Unit ${i + 1}`)
shows no iteration, so when i is called only value of 5 is passed on…
could you please elaborate on this one, i might have some misunderstanding.