There are different ways to empty an array in javascript, we have mentioned 4 ways to clear an array using javascript.
For example we have javascript array variable:
1 |
let arr = [a,b,c]; |
Let’s check out different ways to empty an array.
1) Setting array length to zero:
In this method, set array variable lenght to zero.
1 |
arr.length = 0; |
2) Assign it to new empty array:
This is the quick way to cleat an array in javascript.
1 |
arr = []; |
3) Using pop() method:
using this pop() method you can remove each array element via using while loop.
1 2 3 4 |
while(arr.length > 0) { arr.pop(); } |
This is quite slowest process to empty an array.
4) Use splice() method:
In this way to clear an array, the splice() method will removed all elements and returned the empty array.
1 |
arr.splice(0,arr.length); |