Table of Contents
- Substitution of an empty array
- Assign array’s length to zero
- Using the splice() method
- Using the pop() method
- Using the shift() method
- Other Related Concepts
Substitution of an empty array
This method works as long as the array we want to clear has no references to it. Also, this method is the fastest & easiest way to clear an array.
Assign array’s length to zero
When the length of an array is set to zero, all the array elements are automatically deleted.
Using the splice() methodThe splice() method adds or removes elements to or from an array. It then returns the removed items.
- Index: It is a required parameter that specifies the position to add or remove the elements from an array.
- noOfElements: It is an optional parameter that indicates the number of elements to be removed from the specified Index
- item1, ..., itemN: It is an optional parameter that specifies the new elements to be added at the specified index.
The above example, removes all the elements of an array starting from zero essentially clearing the array.
The splice method returns all the removed elements from an array.
Using the pop() methodThe pop() method removes the last element of an array and returns that element.
We can use this method inside a loop and iterate until the length of the array is greater than zero.
Using the shift() methodSimilar to the pop() method, we could use the shift() method too. The only difference is that the shift() method removes the first element of the array instead of the last element like pop() method.
Overall, the pop() & shift() methods require a longer time & more number of lines of code as we remove elements one by one.