How to Empty an Array in TypeScript


Borislav Hadzhiev

Last updated: Mar 2, 2022


Photo from Unsplash

Empty an Array in TypeScript #

Use the splice() method to empty an array in TypeScript, e.g. arr.splice(0). The method will empty the original array, by removing and returning all its elements starting at index zero. The type of the array is preserved after emptying it.

const arr = [1, 2, 3]; arr.splice(0); // 👇️ const arr: number[] console.log(arr); // 👉️ []

The parameter we passed to the Array.splice method is the start index - the index at which we start changing the array.

The second parameter the splice method takes is delete count - the number of elements that should be removed from the array, from the start index onwards.

If the delete count parameter is not provided, all elements from the start index onwards get deleted.

For our purposes, we provide a start index of 0 to delete all elements and empty the array.

Note that the original type of the array is preserved, even after removing the array's elements.

We didn't explicitly type the array when declaring it, because TypeScript is able to infer the type based on the values.

If you declare an empty array, make sure to explicitly type it, because if you don't TypeScript sets its type to any[], which effectively turns off all type checking.

// 👇️ const arr: any[] const arr = [];
A more performant and better solution is to reassign the variable holding the array.

To empty an array in TypeScript, reassign the variable storing the array and set it to an empty array, e.g. arr = []. Note that you can only reassign variables, declared using the let and var keywords. This is the most performant way to empty an array in TypeScript.

let arr = [1, 2, 3]; arr = []; // 👇️ let arr: number[] console.log(arr); // 👉️ []

Notice that we use the let keyword to to declare the arr variable. Had we used the const keyword, we wouldn't be able to reassign the variable and set it to an empty array.

An alternative approach is to set the array's length to 0.

To empty an array in TypeScript, set its length property to 0. When the length property of an array is changed, every element which has an index that is not smaller than the new length of the array gets automatically deleted.

const arr = [1, 2, 3]; arr.length = 0; // 👇️ const arr: number[] console.log(arr); // 👉️ []

By setting the array's length to 0, we automatically delete all elements from the array with an index that is not smaller than 0, which covers the entire array.

All 3 approaches preserve the type of the array after emptying it.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.