3 Ways to Empty a JavaScript Array

--

The Arrays are for JavaScript developers like 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 = 0console.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 the array. This is perfect if you don’t have any references from other places to the original array. If you do, those references won’t be updated and those places will continue to use the old array.

baratheon = ["Robert", "Renly", "Stannis"]baratheon = []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)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.

Thank you :)

--

--