Borislav Hadzhiev
Wed Mar 02 2022·2 min read
Photo by Tim Gouw
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.
For our purposes, we provide a start index of 0
to delete all elements and
empty the array.
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 = [];
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.