There are several ways to empty an array in JavaScript. Here are a few options:
1 Assign a new empty array to the variable:
let myArray = ['a', 'b', 'c'];
myArray = [];
2 Set the length
property to 0
:
let myArray = ['a', 'b', 'c'];
myArray.length = 0;
3 Use the splice()
method:
let myArray = ['a', 'b', 'c'];
myArray.splice(0, myArray.length);
4 Use the pop()
method in a loop:
let myArray = ['a', 'b', 'c'];
while (myArray.length > 0) {
myArray.pop();
}
Which method you choose will depend on your specific needs and the environment in which you are working.