OneBite.Dev - Coding blog in a bite size

clear an array in javascript

Code snippet for how to how to clear an array in javascript with sample and detail explanation

Using JavaScript, an array is a flexible and efficient data structure that can be easily manipulated in a variety of handy ways. However, there may be times when you need to clear an array, and in this article, we will show you how to do that using straight-forward JavaScript coding.

Clear an Array Using Length Property

let array = [1, 2, 3, 4, 5];
array.length = 0;

Code Explanation for Clear an Array Using Length Property

In this example, we first define an array called array with five elements. Then using the length property of an array, we set the length to 0. This essentially clears the array.

Setting the length property of an array to 0 is a fast and simple method of clearing an array. This is because, in JavaScript, the length property not only returns the count of elements in the array but also has a setter that adjusts the number of elements. Setting the length to 0 removes all elements from the array, effectively clearing it.

Clear an Array Using Splice Method

let array = [1, 2, 3, 4, 5];
array.splice(0, array.length);

Code Explanation for Clear an Array Using Splice Method

In this example, we are still using the same array which has five elements. Then, we use the splice method.

The splice() method changes the content of an array by removing or replacing existing elements. As such, in this case, we use it to remove all elements from the start (index 0) to the end of the array (which is equal to the length of the array).

Unlike setting the length property, this method will work even if the array is referenced from another variable or property.

Knowing how to clear an array is a useful trick in any JavaScript developer’s tool kit. Whether you use the length property or the splice method, both techniques are quick and easy ways to clear an array in JavaScript. By manipulating arrays skillfully, you can create more efficient and effective JavaScript code.

javascript