lobo_tuerto's notes
Home
Blog
Notes
About

Iterate X times with JavaScript

An alternative to using a for construct.

📅Published27 July 2022
🏷️
frontendjavascript

To iterate X 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 X 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 secret sauce here is the spread operator on the constructed array. 😉

References


Got comments or feedback?
Follow me on
v-24390d0