How to initialize a new array with values in JavaScript

By

Learn how to initialize a new JavaScript array of a given length filled with the same value, using the Array() constructor with the ES6 fill() method.

~~~

To initialize a new JavaScript array of a given length, filled with the same value, combine the Array() constructor with fill():

Array(12).fill(0)
//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Array(12) creates an array with a length of 12, but with nothing in it: twelve empty slots. fill(0) then sets every slot to 0.

fill() is a new method introduced in ES6, and it accepts any value:

Array(3).fill('todo')
//['todo', 'todo', 'todo']

It also takes optional start and end indexes, if you only want to fill part of the array:

Array(5).fill(0).fill(1, 0, 2)
//[1, 1, 0, 0, 0]

The end index is not included, so this fills positions 0 and 1.

Why not just map over it?

You might think of creating the empty array and mapping over it to compute each value. That doesn’t work:

Array(5).map((_, i) => i)
//[empty × 5]

The slots in Array(5) are empty, not undefined, and map() skips empty slots entirely. You get back the same holes you started with.

Calling fill() first makes the slots real, so map() runs on them:

Array(5).fill(0).map((_, i) => i)
//[0, 1, 2, 3, 4]

Different values per position

When each element depends on its index, Array.from() does it in one step. Pass an object with a length and a function that computes each value:

Array.from({ length: 5 }, (_, i) => i)
//[0, 1, 2, 3, 4]

Array.from({ length: 5 }, (_, i) => i * 10)
//[0, 10, 20, 30, 40]

This is my go-to for generating sequences of numbers.

Watch out when filling with objects

fill() puts the same value in every slot. With numbers and strings that’s what you want. With objects and arrays it’s a trap, because every slot points to the same one:

const rows = Array(3).fill([])

rows[0].push('first')

rows
//[['first'], ['first'], ['first']]

We pushed into rows[0], but all three slots hold the same array, so the change shows up everywhere.

The fix is Array.from(), which calls the function once per slot and creates a fresh object each time:

const rows = Array.from({ length: 3 }, () => [])

rows[0].push('first')

rows
//[['first'], [], []]
~~~

Related posts about js: