Skip to main content

Command Palette

Search for a command to run...

Create an array and fill it at the same time in JavaScript

Updated
1 min read
Create an array and fill it at the same time in JavaScript

To create an array and fill it at the same time we'll create an Array instance and then we'll use the fill() method.

For example:

const myNumbers = Array(4).fill(0) // [ 0, 0, 0, 0 ]

We place as a parameter to fill() the value we want to place inside the array.

Extra thing!

Another thing we can use about the fill() method is substitute some values of the array with the value we want.

If we have this array:

let myNumbers = [ 1, 2, 3, 4 ]

We can use the fill() method to indicate:

  1. With which value to fill the array

  2. Start of the filling

  3. End of the filling

We can fill the myNumbers array with the 0 number starting at the array position 2 and ending at the position 4, so the values 3 and 4 will be replaced by the zeros:

let myNumbers = [ 1, 2, 3, 4 ]

myNumbers.fill(0,2,4) // [ 1, 2, 0, 0 ]

The fill() method itself won't create new positions and values in the array, it will simply replace them.