# How to populate an array with zeros or objects in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jun 8, 2020, updated Jun 13, 2020. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-array-populate

> A quick article to learn how to populate an array with numbers, strings, or objects using ES6 Array.fill() method in JavaScript.

In JavaScript, you can use the `Array.fill()` method to populate an [array](https://attacomsian.com/blog/javascript-arrays) with a zero or any other value like an [object](https://attacomsian.com/blog/objects-prototypes-classes-javascript#objects) or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.

For example, if you want to create an array with five slots and populate it with `0`, you can do the following:

```javascript
const array = new Array(5).fill(0);

console.log(array);

// [0, 0, 0, 0, 0]
```

You can also specify the position of where to start (default `0`) and end (default `array.length`) the filling. By default, all elements will be filled. Here is an example that specifies filling positions:

```javascript
const fruits = ['?', '?', '?', '?', '?'];

const filled = fruits.fill('?', 2, 4);

console.log(filled);

// ['?', '?', '?', '?', '?']
```

The `Array.fill()` method works great for JavaScript immutable values like strings, numbers, and booleans. What if you want to fill an array with objects?

```javascript
const filled = new Array(3).fill({ pizza: '?' });

console.log(filled);

// [{ pizza: '?' }, { pizza: '?' }, { pizza: '?' }]
```

The above example populates an array with objects, but each slot in the array refers to the same object. So if you modify the object like below:

```javascript
filled[0].pizza = '?';
```

It will update every object in the array because they are all referencing to the same object:

```javascript
[{ pizza: '?' }, { pizza: '?' }, { pizza: '?' }]
```

To fill an array with objects, you should rather use the [Array.from()](https://attacomsian.com/blog/javascript-array-from#initializing-an-array) method. This method creates a new array from an array-like or iterable object:

```javascript
const filled = Array.from({ length: 3 }, () => ({ pizza: '?' }));

filled[0].pizza = '?';

console.log(filled);

// [{ pizza: '?' }, { pizza: '?' }, { pizza: '?' }]
```

## Browser compatibility

The `Array.fill()` method is part of ES6 and only works in modern browsers. However, you can use a [polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Polyfill) to support old browsers like Internet Explorer.

To learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable, take a look at [this article](https://attacomsian.com/blog/javascript-arrays).
