Clear an array in JavaScript
This post will discuss how to clear an array in JavaScript.
1. Using [] operator
The simplest solution is to set the variable holding the array to a new empty array using an array constructor or literal notation. This works fine if we don’t have any other references to the original array. Still, it doesn’t clear any existing references to the original array since the original array remains unchanged.
The following code example demonstrates this behavior:
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; var ref = arr; arr = []; console.log(arr); // [] console.log(ref); // [ 1, 2, 3, 4, 5 ] |
2. Using Array.length
To update any existing references to the array, consider changing the length property of the array. The following program sets the length property of an array to 0, which completely truncates it.
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; var ref = arr; arr.length = 0; console.log(arr); // [] console.log(ref); // [] |
3. Using Array.prototype.splice() function
The splice() method is frequently used in JavaScript for removing existing elements from the array in-place. The following code example demonstrates the usage of the splice() method to empty the content of the array.
|
1 2 3 4 5 6 7 |
var arr = [1, 2, 3, 4, 5]; var ref = arr; arr.splice(0, arr.length); // arr.splice(0) console.log(arr); // [] console.log(ref); // [] |
That’s all about clearing 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 :)