Lets take a couple of steps back and look at a simpler example.
This is the function you want to call multiple times:
function doSomething(x) {
labels.push(`Unit ${x + 1}`);
}
It takes an argument which it uses to create a string, and pushes that string to an array.
Of course this is easy to do with a loop:
for (let i = 0; i < 5; i++) {
doSomething(i);
}
It should be obvious here that we pass the loop variable (i) to our function, which is assigned to parameter x. It's the same as doing:
doSomething(0);
doSomething(1);
...
This code is not reusable though. Say we want to call the function a different number of times, not just (and always) five times.
We can put the loop in a function itself, taking the number of times as a parameter:
function repeat(n) {
for (let i = 0; i < n; i++) {
doSomething(i);
}
}
Now we can call the function as repeat(5) or repeat(10) and it will call doSomething that many times.
However, now we want to call another function multiple times. We could create a second repeat function (with a different name of course), but that is not ideal.
Instead of referring to doSomething directly in repeat, we can change repeat to accept a second parameter whose value should be a function value. This is possible because functions are values like any other in JavaScript:
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
Now we can reuse repeat to call any function we want:
repeat(5, doSomething)
repeat(10, doSomethingElse)
And that's what the code above is doing.
action(i)<- i (the current iteration) is passed into the action.xis not the function. It's a parameter. It might help writing it asrepeat(5, function(x) { ... })Unit ${x +}` is surrounded by a tick rather than a single quote. That is a template literal. ${... } allows you to make a reference to a scoped variable.actionisx => { labels.push('Unit ${x + 1}');}(template literal tick marks changed to single quotes for formatting. Those have to be ticks to work)xis the argument passed into this function.