JavaScript alternative to range() function to iterate over array items

JavaScript doesn’t have a built-in range() function. This can be useful to perform an iteration a certain number of times. As an alternative to this, you can use a JavaScript array.

If you don’t care about the actual values from range(), and just want to iterate “x” number of times, you can do so by filling an array with dummy values, and iterating over the array items with the .map() function. Here’s a simple example of what that looks like.

> Array(5).fill(1).map(i => console.log('hi'))
hi
hi
hi
hi
hi
[ undefined, undefined, undefined, undefined, undefined ]

If you don’t fill the array with dummy values, Node.js will not iterate over the empty array items, which means your arrow function will never actually execute. The .fill(..) function easily populates a value into the array slots, and ultimately allows the arrow function to iterate over them as you’d expect it to.