JS functional programming for n elements

I am trying to write code in a more functional style, and the problem I am facing is to populate an array of elements n.

For instance:

const items[];

for (let i = 0; i < n; i++) {
    items.push(new Item());
}

If I understand correctly, there are two side effects: imutates itemsas well.

I am wondering what a "clean" way to do this in Javascript is. I tried things like (new Array(n)).map(...)and (new Array(n)).forEach(...), but I'm not sure why it would be better or worse. Can someone clarify or point me to a message that covers this topic?

+4
source share
1 answer

This solution seems to be a good option:

const n = 10;
const items = Array.from(Array(n), x => new Item());

Array.from().


Javascript.

+2

All Articles