How to Fill an Array with Defaults

The Array built-in function, the fill and map array methods, and more

Cristian Salcescu
Frontend Essentials

--

There are cases when we want to create an array filled with default values. For small arrays, of course, we can just write down the values when declaring the array but for larger arrays, a nicer system may be needed.

const arr = [false, false, false, false, false];

Let’s try to do the previous initialization in a nicer way.

Initialize with Primitives

Array(length)

The Array built-in function can be used to create an array with the specified length but with no actual values in it.

Array(5) gives an array of length 5 but with no values.

const arr = Array(5);
console.log(arr.length);
//5

fill(defaultValue)

The fill() method changes all elements in an array to a default value. It begins from a start index (default 0) to the end index (default array.length) and returns the modified array. fill is an impure method, it changes the input array.

Below is an example of resetting all values of an array to false.

const arr = [true, false, true];
arr.fill(false);

--

--