How to empty an array in JavaScript ?
There are many ways to empty an array using JavaScript. In this article, we will discuss and execute the top three ways to make an array empty.
- Setting the array to a new array.
- By using the length property to set the array length to zero.
- By using the pop() method we will be popping each element of the array.
Below examples will illustrate the above-mentioned ways to empty an array.
Example 1: Setting to a new Array means setting the array variable to a new array of size zero, then it will work perfectly.
Javascript
let Arr = [1, 2, 3, 4, 5];
console.log( "Array Elements: " + Arr);
console.log( "Array Length: " + Arr.length);
function emptyArray() {
Arr = [];
console.log( "Empty Array Elements: " + Arr);
console.log( "Empty Array Length: " + Arr.length);
}
emptyArray();
|
Output
Array Elements: 1,2,3,4,5
Array Length: 5
Empty Array Elements:
Empty Array Length: 0
Example 2: By using the length property, we set the length of the array to zero which will make the array an empty array.
Javascript
let Arr = [1, 2, 3, 4, 5];
console.log( "Array Elements: " + Arr);
console.log( "Array Length: " + Arr.length);
function emptyArray() {
Arr.length = 0;
console.log( "Empty Array Elements: " + Arr);
console.log( "Empty Array Length: " + Arr.length);
}
emptyArray();
|
Output
Array Elements: 1,2,3,4,5
Array Length: 5
Empty Array Elements:
Empty Array Length: 0
Example 3: By using pop() method on each element of the array, we pop up the array element continuously and get an empty array. But this method takes more time than others and is not much preferred.
Javascript
let Arr = [1, 2, 3, 4, 5];
console.log( "Array Elements: " + Arr);
console.log( "Array Length: " + Arr.length);
function emptyArray() {
while (Arr.length > 0) {
Arr.pop();
}
console.log( "Empty Array Elements: " + Arr);
console.log( "Empty Array Length: " + Arr.length);
}
emptyArray();
|
Output
Array Elements: 1,2,3,4,5
Array Length: 5
Empty Array Elements:
Empty Array Length: 0
Last Updated :
21 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...