Two ways to clear an array with vanilla JavaScript
Contents
Thanks to all authors for creating a page that has been read 14,688 times. Include your email address to get a message when this question is answered. Social login does not work in incognito and private browsers. Please log in with your username or email to continue.
- Unfortunately, there is no simple Array.prototype.clear method to clear the whole array.
- Find centralized, trusted content and collaborate around the technologies you use most.
- Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions.
- There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.
- This method can also work in case of “strict mode” in ECMAScript 5 because the length property is a read/write property.
- @BekimBacaj i have updated my answer, I just assumed that length pops till length, but i corrected now that length just truncates or increases the size of an array.
The array.length is a built-in JavaScript property that sets or returns the number of items in the array. This comes with the downside of creating a new array and leaving the old one for the garbage collector. Garbage collection is an optimized process in nowadays Node.js runtimes.
References
The above example, removes all the elements of an array starting from zero essentially clearing the array. When the length of an array is set to zero, all the array elements are automatically deleted. We continue with Flexiple’s tutorial series to explain the code and concept behind common use cases. In this blog, we look at the different methods to clear/empty an array using JavaScript. This is perfect if you don’t have any references from other places to the original arr. If you do, those references won’t be updated and those places will continue to use the old array.
@BekimBacaj No, splice mutates the original array and returns a new array. It is “frowned upon” to modify javascript primitive functions like Array and String. You could possibly be overloading an already existing function and trash the object class.
Clear an array using JavaScript
But sometimes, you have an array that’s assigned by reference, and you want to keep them linked. In most situations, reassigning the variable to an empty array is the better choice. It’s shorter and more explicit than adjusting the length property. Setting the length to zero will empty the existing array. In a blog post, David Walsh mentions two approaches for emptying an array. This blog post explains the pros and cons of both approaches.
Using a new array will not affect any value that references your array. Depending on where this array comes from this is safe to use because you’re not changing the values themselves. We can reset the value of the element of an array using the set method. It only requires the index position of the element to reset and the new value. This is the best way to reset/clear/empty an array in JavaScript. It isunambiguousand will affect both the variable containing the array and any variables referencing the array.
A lot of answers here are old and I wouldn’t rely on them but rather test as in @tanguy_k’s answer above. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty. Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4.
In Javascript how to empty an array
This function will return a copy of the array before deleting the entries, which is helpful if you want to do a reassignment before clearing the array. In this example, first, the b variable references the array a. If I instead https://forexaggregator.com/ set the length of wizards to 0, the alsoWizards variable is also an empty array, because the array that wizards points to has not changed. I also have an alsoWizards variable, and I set its value to the wizards array.
There are three primary ways to clear an array—replacing the array with a new array, setting its property length to zero, and splicing the array. These three methods work similarly, although replacing the array with a new array shouldn’t be used if other code references the original array. The splice method returns all the removed elements from an array. In this solution, the splice() method removed all the elements of the a array and returned the removed elements as an array. You will want to use the trash bin icon at the bottom to force a garbage collection after ‘clearing’ the array. This should give you a more definite answer for the browser of your choice.
There might be an obscure javascript engine that already has clear() and expects it to behave a different way. That doesn’t necessarily mean they will shrink the storage for the actual array immediately. Another way to clear an array is to set the array’s length property to 0.
This is perfect if you don’t have references to the original array A anywhere else because this actually creates a brand new array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A. Setting it to 0 means, we are emptying the array. It removes each item in the array, which does hit other references. The third method is using .splice(), which will work fine.
However, it will return a copy of the original array as the function returns an array with all the removed items. I tried it on most of browsers, like IE, Firefox, Chrome, it is creating new array. If you set length greater than 0 then it will create an array with undefined elements, i.e. it will just hold some memory locations. When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.
How to Reset/Clear/Empty an Array in JavaScript
The splice() method adds or removes elements to or from an array. This will clear the existing array by setting its length to 0. Fast solution, but this won’t free up the objects in this array and may have some memory implications. In order to clean objects in array from memory, they need to be explicitly removed. JavaScript arrays enable you to group values and iterate over each item.
When you decrease it, the array will be truncated. Use this method if you only reference the array by its original variable arr. The original array The Ultimate Guide to Create A Social Media App Development will remain unchanged if you have referenced this array from another variable or property. A more verbose approach is to use the splice() method.
In addition, you can append and remove array elements in different ways. Unfortunately, there is no simple Array.prototype.clear method to clear the whole array. Using this approach, you don’t leave work for the garbage collector, but possibly affect referenced arrays and reset them as well. All JavaScript runtimes (Browser, Node.js) are optimized for the operation to set the array length to zero. This code will set the variable A to a new empty array.
We can use this method inside a loop and iterate until the length of the array is greater than zero. The simplest solution is to assign the array’s length to the value of 0. You can reassign a new value to a variable that initially has a non-empty array assigned to it. With a length of 0, every value in the array gets removed, and the array becomes empty. The length property of an array is readable and writeable. The following shows you several methods to make an array empty.
Benchmarks suggest that this has no effect on performance whatsoever. In the above code, the splice() method emptied the array as all the elements were removed. Overall, the pop() & shift() methods require a longer time & more number of lines of code as we remove elements one by one.