In JavaScript, you can empty an array using various approaches. Here are some common methods to empty an array in JavaScript:
Method 1: Reassigning the array to an empty array
One of the simplest ways to empty an array is to reassign it to an empty array. Here’s an example:
let arr = [1, 2, 3, 4, 5];
arr = [];
console.log(arr); // Output: []
Code language: JavaScript (javascript)
In the example above, we assigned an empty array to the arr variable, which cleared the contents of the original array.
Method 2: Using the splice() method
Another approach to empty an array is by using the splice() method. This method is used to add or remove elements from an array, but if we pass 0 as the second parameter, it will remove all the elements from the array.
let arr = [1, 2, 3, 4, 5];
arr.splice(0, arr.length);
console.log(arr); // Output: []
Code language: JavaScript (javascript)
In the example above, we used the splice() method to remove all elements starting at index 0 to the end of the array.
Method 3: Using the length property
We can also use the length property of an array to empty it. By setting the length of the array to 0, we can remove all the elements from the array.
let arr = [1, 2, 3, 4, 5];<br>arr.length = 0;<br>console.log(arr); // Output: []
Code language: JavaScript (javascript)
In the example above, we set the length of the arr array to 0, which removed all the elements from the array.
Method 4: Using the pop() method
We can also use the pop() method to remove all elements from an array. This method removes the last element of the array, and we can call it repeatedly until the array is empty.
let arr = [1, 2, 3, 4, 5];
while (arr.length) {
arr.pop();
}
console.log(arr); // Output: []
Code language: JavaScript (javascript)
In the example above, we used a while loop to call the pop() method repeatedly until the array is empty.
These are some common ways to empty an array in JavaScript. You can choose the method that suits your needs and programming style.