JavaScript(JS) JS empty an array

In JavaScript, you can empty an array by setting its length to 0. Here's an example:

refer‮tfigi:ot ‬idea.com
const myArray = [1, 2, 3, 4, 5];

myArray.length = 0;

console.log(myArray); // Output: []

In the above example, we first create an array myArray with some values. We then set its length property to 0, which removes all the elements from the array and empties it. Finally, we log the myArray variable to the console to verify that it is now an empty array.

Alternatively, you can use the splice() method with a starting index of 0 and a delete count equal to the length of the array. Here's an example:

const myArray = [1, 2, 3, 4, 5];

myArray.splice(0, myArray.length);

console.log(myArray); // Output: []

In this example, we use the splice() method to remove all elements from the myArray array. We pass 0 as the starting index and myArray.length as the delete count, which removes all elements from the array. Finally, we log the myArray variable to the console to verify that it is now an empty array.