How to Clear Array in TypeScript

In this post, we will see how to clear array in Typescript.

There are multiple ways to do it. Let’s go through them.

1. By setting array’s length to 0

To clear array in TypeScript:

  • Set length of array to 0.
  • When length property is changed, all the elements that have index larger than its length automatically get deleted.

Output:

2. Using splice() Method

To clear array in TypeScript:

  • Use Array.splice() method with start index as 0 and it will clear the array.

Let’s see with the help of simple example:

Output:

We have passed start index as 0 to Array.splice(). start index is the index at which we want to change the array.

We can also pass second parameter deleteCount i.e. number of elements to be deleted after start index.

If we don’t provide start index, then it will delete all elements starting from start index.

3. By Reassigning the Variable

To clear array in TypeScript:

  • Reassign the variable storing the array to empty array. arrNum= [].

Let’s see with the help of simple example:

Output:

Please note that you can not reassign variable if you use const to declare the variable. If you try to do it, you will get TypeError: Assignment to constant variable.

This is better approach performance wise.

4. Using pop() method

To clear array in TypeScript:

  • Iterate over array using for or while loop.
  • Use Array.pop() method to remove element from the array.
  • When loop ends, all the elements will be removed from the array.

Please note that this solution is slowest among all the other solutions.

Let’s see with the help of example:

Output:

That’s all about how to clear array in TypeScript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *