Javascript: How to Clear an Array

By Henri Parviainen

How to clear javascript array

There are multiple ways to clear a populated array in Javascript. In this post, we will introduce the most common methods to remove elements from array.

Method 1 - Assign a new empty array as a value

We can clear an array by assigning a new empty array as its value.

let languages = ["Javascript", "Python", "C"];
languages = [  ];

console.log(languages);

// Prints [  ]

This method works as long as you don't have any references pointing to the original array.

See the example code below.

let languages = ["Javascript", "Python", "C"];

let courses = languages;

languages = [  ];

console.log(courses);

// Prints ['Javascript', 'Python', 'C']

When to use empty array assignment?

Use this method when you want to clear the original array but also want to keep all the references unchanged or if you don't have any references.

Method 2 - Set array length to 0

Another method we can use to clear an array is to set its length property to zero. If we set array length to zero, all elements of the array will be deleted. This includes all reference arrays as well.

languages.length = 0;

console.log(languages);

// Prints [ ]

console.log(courses);

// Prints [ ]

When to use array.length = 0?

Use this method when you want to clear both the original array and all references it may have. This is the most recommended and fastest way to remove all array elements from the whole array.

Method 3 - Using splice

We can also empty all values from array with a splice array method.

languages.splice(0, languages.length);

console.log(languages);

// Prints []

The first parameter we give to splice is the index where we start. In the second parameter, we define how many indexes will be removed.

When to use splice?

Splice works just like method 2 so you can use it if you want to clear the array content as well as all references.

SHARE