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); //[]