How to fill an array with a specific value in JavaScript?

November 23, 2020 - 2 min read

To fill an array with a specific value, you can use the fill() array method in JavaScript.

Consider this array of numbers,

// number array
const numArr = [1, 2, 3, 4, 5];

Let's use the fill() array method to fill the entire array with value 9 by passing value as the first argument to the method like this,

// number array
const numArr = [1, 2, 3, 4, 5];

// fill the entire array
// with value 9 using the fill() method
numArr.fill(9);

console.log(numArr); // [9, 9, 9, 9, 9]

See this example live in JSBin.

If you don't want the whole array to be filled with a specific element but from one index to another index in the array, you can pass the start index as the second argument and end index as the third argument to the fill() method like this,

// number array
const numArr = [1, 2, 3, 4, 5];

// fill the entire array
// with value 9 but from index 1 to 3
// using the fill() method
numArr.fill(9, 1, 3);

console.log(numArr); // [1, 9, 9, 4, 5]

The method will start filling from the start index and ends without filling the end index.

See this example live in JSBin.

Feel free to share if you found this useful 😃.