Create a Zero filled array in TypeScript

avatar

Borislav Hadzhiev

Thu Mar 03 20222 min read

banner

Photo by Seth Doyle

Create a Zero filled array in TypeScript #

Use the fill() method to create an array filled with zeros in TypeScript, e.g. const arr1: number[] = new Array(4).fill(0). The fill() method sets the elements in the array to the provided value and returns the modified array.

index.ts
// 👇️ const arr1: number[] const arr1: number[] = new Array(4).fill(0); console.log(arr1); // 👉️ [0, 0, 0, 0]

The only parameter we passed to the Array() constructor is the number of empty elements the array should contain.

index.ts
// 👇️ const arrOf4: any[] const arrOf4 = new Array(4); console.log(arrOf4); // 👉️ [ , , , ]

You can imagine that using the Array constructor is like creating an empty array and setting its length.

Note that the type of the created array is inferred to be any[].

This is why we explicitly typed the array as number[] in the example.

index.ts
// 👇️ const arr1: number[] const arr1: number[] = new Array(4).fill(0); console.log(arr1); // 👉️ [0, 0, 0, 0]

If you don't explicitly type the array it will have a type of any[], which effectively turns of all type checking.

The next step is to call the fill() method on the array.

The only parameter we passed to the fill method is the value we want to fill the array with.

Each of the 4 elements in the array get assigned a value of 0.

Create a Zero filled Array using a for loop #

To create a zero filled array in TypeScript:

  1. Use the Array() constructor to create an array of variable length.
  2. Use a for loop to iterate over the array.
  3. On each iteration, assign the element to 0.
index.ts
const arr: number[] = new Array(4); for (let i = 0; i < arr.length; i++) { arr[i] = 0; } console.log(arr); // 👉️ [0, 0, 0, 0]

We used the Array() constructor to create an array containing 4 empty elements.

The for loop allows us to iterate over the array and assign each empty element to zero.

Which approach you pick is a matter of personal preference. I'd go with using fill() since it is easier to read and more concise.

Use the search field on my Home Page to filter through my more than 1,000 articles.