How to create an array with N empty elements in javascript


While revising an internal code, I stumbled upon the following construct:

Array.from({length: n});

This was new for me, and I though: what the hell is this? This cannot be regular javascript. I started debugging and realized that what developer wanted to do was to create an array with n empty items. And it seems that this is one of the many valid ways of doing that.

Why not simply use new Array(n)?

The first thing that came into my mind is why didn’t he simply do:

new Array(n);

This isn’t clearly document in the Array constructor, but when you use the Array constructor passing the arrayLength parameter, the length is set to arrayLength but the array is not initialized with empty values.

Looking at Chrome’s console is easy to understand the difference:

> new Array(3)
(3) [empty × 3]

> Array.from({ length: 3 })
(3) [undefined, undefined, undefined]

Other ways to achieve the same behaviour

If you still want to use the Array constructor, there are other ways to create an array with undefined values:

> [...new Array(3)]
(3) [undefined, undefined, undefined]

> new Array(3).fill(undefined)
(3) [undefined, undefined, undefined]

Initializing the array with values from 0 to N-1

If you want to create an empty arrays with values from 0 to N-1 (or from 1 to N) there are different ways to achieve based on this thread:

Using ES6:

Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// or

[...Array(10).keys()]
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// from 1 to N

Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Without ES6:

> new Int8Array(10).map((curr, index) => curr = index + 1)

Leave a comment

Your email address will not be published. Required fields are marked *