Eloquent Javascript - Abstracting repetition

Hello everyone,

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?

the second code:

let labels = [];
repeat(5, i => {
  labels.push(`Unit ${i + 1}`);
});
console.log(labels);
// → ["Unit 1", "Unit 2", "Unit 3", "Unit 4", "Unit 5"]

my question to this code is, how in the world this code do iteration? i don’t see i is defined as something that will iterate here?

Hi,

for the first question.

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

i => {
  labels.push(`Unit ${i + 1}`);
}

this could have had a reference for example

const pushStuff = i => {
  labels.push(`Unit ${i + 1}`);
}

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.
1 Like

Hello George,

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.

and thank you for your kind words. :')

aha! thanks for pointing it out.

I’ve been looking at it as 2 separated code that’s why. now I got it, thank you Randell!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.