How to Empty an Array in Javascript?
There are multiple ways to empty an array in JavaScript:
- Setting the length property of the array to zero
You can set the length property of the array to zero to delete all the elements inside it.
Example:
let arr = [1, 2, 3, 4];
arr.length = 0;
console.log(arr); // []
- Using the splice() method
The splice() method can be used to remove elements from an array. You can use it to remove all the elements of an array.
Example:
let arr = [1, 2, 3, 4];
arr.splice(0, arr.length);
console.log(arr); // []
- Using the pop() method in a loop
You can use the pop() method in a loop until all the elements are removed from the array.
Example:
let arr = [1, 2, 3, 4];
while (arr.length) {
arr.pop();
}
console.log(arr); // []
- Using the shift() method in a loop
You can use the shift() method in a loop until all the elements are removed from the array.
Example:
let arr = [1, 2, 3, 4];
while (arr.length) {
arr.shift();
}
console.log(arr); // []