Different ways to empty array in JavaScript

June 27, 2020

4 ways you can empty array

  • Set length as 0
  • Assign to empty array
  • Splice the array
  • pop elements until the length of array is 0

Set length of array as 0

When we set length property of an array to 0 then, all elements in the array are removed

let numbers = [1, 2, 3, 4, 5];
numbers.length = 0;
console.log(numbers);   // []

Assign to empty array

let numbers = [1, 2, 3, 4, 5];
numbers = [];
console.log(numbers); // []


Splice the array

The splice() method alters the content of the array by removing/replacing existing elements and/or adding new elements in place(in original array)

parameter splice(startIndex, deleteCount, ...elementsToInsert)

Example

let a = ['one', 'two', 'three'];
a.splice(1,2); //removes 2 elements from index 1
console.log(a); // ["one"]

So if we call splice method by passing , startIndex → 0 and deleteCount → length of array, it will delete all elements

let numbers = [1, 2, 3, 4, 5];
numbers = numbers.splice(0, numbers.length);
console.log(numbers); // []

pop elements until the length of array is 0

We will remove the last element of the array until the array has elements

let numbers = [1, 2, 3, 4, 5];
while (numbers.length) {
    numbers.pop();
}