The Arrays are for JavaScript developers like how screws and nails are for carpenters. Hence it is important to know the in and around with how it works. Emptying an array is one of the important concepts involved so here are the few methods I know.
1) Using length property
The length
property returns the number of elements in that array. And if we equate this to 0
, we will be able to empty the array elements. This method is quite popular but not the fastest way to do the job.
baratheon = ["Robert", "Renly", "Stannis"]
baratheon.length = 0 // empties array
console.log(baratheon) // expected result: []
console.log(baratheon.length) // expected result: 0
2) Assigning it to a new empty array
This is the fastest way of emptying an array. 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.
baratheon = ["Robert", "Renly", "Stannis"]
baratheon = [] // empties array
console.log(baratheon.length) // expected result: 0
console.log(baratheon) //expected result: []
3) Using Array method splice()
This can be done using the splice()
method from the list of JavaScript Array methods. The splice()
method takes the index (from which the splicing should start ) and the number of items to be removed as parameters and splices the elements.
We have to pass the 0
as index (the first element) and the length of the array as parameters which ends up emptying the whole array. The performance of this method is almost as fast as assigning the new array method.
baratheon = ["Robert", "Renly", "Stannis"]
baratheon.splice(0, baratheon.length) // empties array
console.log(baratheon.length) // expected result: 0
console.log(baratheon) //expected result: []
And that sums it up. Comment below if you know any other ways to empty an array.
Top comments (10)
Whoah, I never knew
Array#length
was settable!Setting it almost seems like an antipattern, because you'd expect it to be a read-only property, but it also looks to be the cleanest way to empty an array in-place (the
splice
version is even less intuitive).I guess this would be one example where a comment explaining "what" (rather than "why" or "how") would be useful.
Noted. I'll add the comment. It can be confusing.
Your Topics are interesting ๐
Which method do you think will be the best in case of readability and performance?
I will chose assigning it to a new empty array
baratheon = []
Assigning it to new empty array is the faster way.
Good post Sanchithasr!
I know another, but it's slower in terms of performance
Yes. It's very slow when it comes to performance.
Very interesting didn't know about
but look's cleaner , THANK YOU
please add the javascript tag to the codeblocks
Done. Thanks for the suggestion.
This is... "advanced"???
Some comments have been hidden by the post's author - find out more