Home

Run Loop n Times in JavaScript

Quick snippet to run some function n times using JavaScript.

I run into the situation frequently in which I want to iterate n number of times over a loop. As a former Rubyist, I loved being able to do this:

10.times do
# runs 10 times
end

Using classic JavaScript patterns, you could do something like this:

for (i = 1; i <= 10; i++) {
// runs 10 times
}

But that feels ... old, doesn't it?

Here's a fancy way to do this with more modern JavaScript:

Array(10)
.fill()
.map(() => {
// runs 10 times
});

There are several quirks that makes this work the way it does. If you're curious and want to go deep, here is a great in-depth look at creating arrays in JavaScript.

Let's Connect

Keep Reading

WTF is JavaScript?

A brief description of JavaScript, with a few links to dig in and learn more.

Jun 29, 2020

Better Website Performance with Pixelated Placeholder Images

Page load times decrease as the number of images on a page increase. Learn the pixelated placeholder method that mitigates performance issues caused by images without negatively impacting user experience.

Jan 09, 2019

WTF is Hoisting?

Sometimes JavaScript code appears to behave oddly. Hoisting is one of the reasons why. Here's an introduction to the concept, with references to more in-depth explorations.

Aug 07, 2020