Delete all elements from an array in JavaScript
This post will discuss how to delete all elements from an array in JavaScript.
There are several ways to delete all elements from an array in JavaScript. Here are some examples of how to delete all elements from an array in JavaScript given an array:
1. Using length
property
The length
property reflects the number of elements in an array. We can use it to delete all elements from an array by setting it to zero. This is a simple and efficient way to empty an array in JavaScript. For example, if we have an array [1, 2, 3, 4, 5]
and we want to delete all elements, we can do:
1 2 3 4 5 6 |
var arr = [1, 2, 3, 4, 5]; // set the length of the array to zero arr.length = 0; console.log(arr); // [] |
2. Using splice()
function
The Array.splice() function changes the contents of an array by removing existing elements and/or adding new elements. We can pass a start index of zero and a delete count equal to the length of the array. This will delete all elements from the array and return a new array containing the removed elements. For example, if we have an array [1, 2, 3, 4, 5]
and we want to delete all elements, we can do:
1 2 3 4 5 6 |
var arr = [1, 2, 3, 4, 5]; // delete all elements from the beginning arr.splice(0, arr.length); console.log(arr); // [] |
3. Using array literal
We can use array literal to create a new empty array and assign it to the variable that holds the original array. This way, we can delete all elements from an array without modifying it. However, any existing references to the original array will not be discarded. The following code illustrates this:
1 2 3 4 5 6 7 8 |
var arr = [1, 2, 3, 4, 5]; var arr_ref = arr; // Assign a new empty array to the original variable arr = []; console.log(arr); // [] console.log(arr_ref); // [1, 2, 3, 4, 5] |
That’s all about deleting all elements from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)