Skip to content

Empty an array in JavaScript

In this post we will discuss the different ways to empty an array in JavaScript. Let’s declare an array for explanation purposes.

Advertisements
let arr = [1,2,3,4,5];

Setting length to 0

arr.length = 0;
console.log(arr);
//[]

Assigning to empty array

arr = [];
console.log(arr);
//[]
Advertisements

Remove all the array elements

while (arr.length > 0) {
	arr.pop();
}

console.log(arr);
//[]

Splice the array

arr.splice(0, arr.length);

console.log(arr);
//[]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.