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)

1
  • "What I was trying to accomplish was initializing an array of objects like the following:" then use Array.from({length: 5}, () => ({name:''})) Commented Jan 28, 2021 at 21:23

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

would you recommend doing this? const names = [...new Array(5)].map( () => ({name:''}))
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);

Comments

1

You can fill your array like:

const array = new Array(5).fill({ name: '' });

2 Comments

no. you get the same object at every index.
You are right @Zac, I get the same object. This would be perfect for primitive values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.