There are several ways to empty an array in JavaScript:
- You can use the ‘
length
‘ property to reset the length of the array to zero:
let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); // []
2. You can use the ‘splice()
‘ method to remove all elements from the array:
let arr = [1, 2, 3, 4, 5];
arr.splice(0, arr.length);
console.log(arr); // []
3. You can use the ‘pop()
‘ method in a loop to remove all elements from the array:
let arr = [1, 2, 3, 4, 5];
while (arr.length > 0) {
arr.pop();
}
console.log(arr); // []
4. You can use the ‘shift()
‘ method in a loop to remove all elements from the beginning of the array:
let arr = [1, 2, 3, 4, 5];
while (arr.length > 0) {
arr.shift();
}
console.log(arr); // []
5. You can use the ‘slice()
‘ method to create a new, empty array:
let arr = [1, 2, 3, 4, 5];
arr = arr.slice(0, 0);
console.log(arr); // []
6. You can use the ‘filter()
‘ method to create a new, empty array:
let arr = [1, 2, 3, 4, 5];
arr = arr.filter(() => false);
console.log(arr); // []
Each of these methods will empty the array, but they have different performance characteristics and may be more or less appropriate depending on the specific use case.
RELATED : What is the JavaScript version of sleep()? [All Methods]