How to initialize an Array with Zeros or Objects in JavaScript

Updated onbyAlan Morel
How to initialize an Array with Zeros or Objects in JavaScript

When you are working with arrays, sometimes you'll need to overwrite every element of the array with a specific value.

In JavaScript, this is called filling the array.

In this post, we'll learn how we can fill in an array with any value you want, including zeros and objects.

Filling an Array with Zeros

Let's start with an easy example, such as creating a new array, and then filling it with zeros.

To do this, we'll make use of the built-in fill() method.

JAVASCRIPT
const array = new Array(3); array.fill(0); console.log(array);
BASH
(3) [0, 0, 0]

The fill() method takes three parameters, the first is the value to fill the array with, the second is the start index, and the third is the end index.

The start and end index are optional, and if they are not specified, the fill will start at the beginning of the array and go to the end.

Let's look at filling in only the last two elements of the array.

JAVASCRIPT
const array = new Array(3); array.fill(1, 1, array.length); console.log(array);
BASH
(3) [empty, 1, 1]

Filling an Array with Objects

The fill() method can also be used to fill an array with objects.

JAVASCRIPT
const array = new Array(3); const value = { name: "sabe.io:" }; array.fill(value); console.log(array);
BASH
(3) [{…}, {…}, {…}] 0: {name: 'sabe.io:'} 1: {name: 'sabe.io:'} 2: {name: 'sabe.io:'} length: 3

Keep in mind that since you are filling this array with the same object, they will all have the same reference.

This means that modifying one of the objects will modify all of them.

Let's see this in action:

JAVASCRIPT
const array = new Array(3); const value = { name: "sabe.io:" }; array.fill(value); array[0].name = "sabe.io/hello"; console.log(array);
BASH
(3) [{…}, {…}, {…}] 0: {name: 'sabe.io/hello'} 1: {name: 'sabe.io/hello'} 2: {name: 'sabe.io/hello'} length: 3

To avoid this scenario, you can use the Array.from() method, which will create and automatically populate your array with your specified value:

JAVASCRIPT
const value = () => ({ name: "sabe.io" }); const array = Array.from({ length: 3 }, value); array[0].name = "sabe.io/hello"; console.log(array);
BASH
(3) [{…}, {…}, {…}] 0: {name: 'sabe.io/hello'} 1: {name: 'sabe.io'} 2: {name: 'sabe.io'} length: 3

As you can see, the first element of the array is now modified, but the other two are not, which is what you want.

Conclusion

In this post, we looked at how to fill an array with zeros, and how to properly fill an array with objects.

Simply use the fill() method to fill in your array with any value you want, which also includes strings.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.