2022 / 07 / 27
TIL: Iterate an arbitrary number of times with forEach in JavaScript

Or generate an arbitrary number of objects with map

javascript

To iterate n number of times, just use forEach like this:

const count = 50

[...Array(count)].forEach((_, index) => {
  console.log(`Line: ${index}`)
})

// Line: 0
// Line: 1
// ...

Other times you might want to build an array of n number of objects — usually when creating demo data.

I’ve found that a simple way to do that is:

const count = 50

[...Array(count)].map((_, index) => {
  return {
    id: index,
    value: Math.random() * 100
  }
})

// [ { id: 0, value: 13.144746993948909 },
//   { id: 1, value: 9.09769909468544 },
//   ...

The key here, is the spread operator on the constructed array. ;)

References