Sometimes, we want to run code repeatedly for x
times with JavaScript without using a mutable variable.
In this article, we’ll look at how to run code repeatedly for x
times with JavaScript without using a mutable variable.
Using the Array Constructor, Spread Operator, and Array.prototype.map
We can create an array with length x
with the Array
constructor, and then call the map
method to return the result we want.
For instance, we can write:
const res = [...Array(10)].map((_, i) => {
return i * 10;
});
console.log(res)
We create an array with 10 empty slots with Array(10)
.
Then we spread that into a new array, then we call map
to return the element we want in the returned array.
We get the index i
, multiply it by 10 and return it.
Therefore, res
is:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Using the Array Constructor, Spread Operator, and Array.prototype.forEach
If we don’t want to return a new array after running our code repeatedly, we can also call the forEach
method on the empty array instead of map
.
For example, we can write:
[...Array(10)].forEach((_, i) => {
console.log(i);
});
We just log the index i
value in the forEach
callback.
And so we get 0, 1, 2,…, all the way up to 9 logged from the console log.
Using the Array.from Method
We can also sue the Array.from
method to create an empty array and then use Array.prototype.map
to map the empty array into an array of values we want.
For instance, we can write:
const res = Array.from(Array(10)).map((_, i) => {
return i * 10;
});
console.log(res)
And then we get the same result as the first example.
Conclusion
We can run code repeatedly for x
times without create a loop with a mutable index variable with JavaScript array methods and the spread operator.