In this article, you’ll learn how to clear an array in Javascript. Here, clearing an array means removing all the elements from the array and leaving an empty array.
Here are 4 ways to clear out an array:
In this example, you can simply set the variable “Array” to a new empty array. This is perfect if you don't have references to the original array “Array” anywhere else because this actually creates a brand new (empty) array. Let’s take an example:
let Array = [1, 2, 5, 7, 10, 15];
console.log("Original Array Length: "+ Array.length)
//Output ==> "Original Array Length: 6"
Array = [];
console.log("After Clearing, Array Length: "+ Array.length)
//Output ==> "After Clearing, Array Length: 0"
In this example, you can set the array length to 0, this will clear the existing array. Let’s take an example:
let Array = [1, 2, 5, 7, 10, 15];
console.log("Original Array Length: "+ Array.length)
//Output ==> "Original Array Length: 6"
Array.length = 0;
console.log("After Clearing, Array Length: "+ Array.length)
//Output ==> "After Clearing, Array Length: 0"
In this example, you can use the .splice()
function and it will return an array with all the removed items, it will actually return a copy of the original array. Let’s take an example:
let Array = [1, 2, 5, 7, 10, 15];
console.log("Original Array Length: "+ Array.length)
//Output ==> "Original Array Length: 6"
Array.splice(0, Array.length)
console.log("After Clearing, Array Length: "+ Array.length)
//Output ==> "After Clearing, Array Length: 0"
In this example, we used pop()
method and while
loop. It will remove the element from the array one by one. Let’s take an example:
let Array = [1, 2, 5, 7, 10, 15];
console.log("Original Array Length: "+ Array.length)
//Output ==> "Original Array Length: 6"
while(Array.length > 0) {
Array.pop();
}
console.log("After Clearing, Array Length: "+ Array.length)
//Output ==> "After Clearing, Array Length: 0"
I hope this article will help you to understand how to clear an array in Javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments