3

If I have the following:

const array = new Array(5)
console.log(array)

array.forEach(() => console.log('Hello')) // does not work

I would expect to see 5 'Hellos', but it seems JS doesn't even get into the loop. Why?

What I was trying to accomplish was initializing an array of objects like the following:

const users = (new Array(5)).map(() => ({name:''}))

console.log(users)
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
Antuan
  • 501
  • 2
  • 6
  • 18
  • "*What I was trying to accomplish was initializing an array of objects like the following:*" then use `Array.from({length: 5}, () => ({name:''}))` – VLAZ Jan 28 '21 at 21:23

3 Answers3

2

.map and .foEach loop over each item in the Array, by doing new Array(5) you get an array of length 5, but it's empty, nothing to loop over, you still need to fill it with items

Zac
  • 1,497
  • 9
  • 11
1

You can fill your array like:

const array = new Array(5).fill({ name: '' });
AdriSolid
  • 2,570
  • 1
  • 7
  • 17
1

Try this:

const result = Array.apply(null, new Array(5)).map(() => ({name:''}));
console.log(result);

Or this:

const result = [...new Array(5)].map(() => ({name:''}));
console.log(result);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48