How to clear an array in JavaScript

Jan 16, 2024#javascript#arrays

When you say “clear the array” in the context of programming, it generally means removing all the elements from the array, leaving it empty. Essentially, you want the array to have a length of zero, and no elements stored in it.

Clearing an array is often necessary when you need to reset or prepare the array for new data without creating a new array instance. It’s a way to free up memory and start with a clean slate.

In JavaScript, all methods such as setting the length to 0, using splice(), or assigning a new empty array, all achieve the goal of clearing the array. Choose the method that best suits your coding style and requirements.

  1. Assigning an empty array, essentially discarding the reference to the old array, generally the most efficient and recommended approach.
let arr = [1, 2, 3, 4, 5];
arr = [];
console.log(arr); // []
  1. Setting the length property to zero, also efficient and directly modifies the original array. If you set it to a value less than the current length, the array will be truncated, removing elements from the end. If you set it to a value greater than the current length, the array will be extended, and new elements will be filled with undefined.
let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); // []
  1. Using the splice() method, useful when you need to remove a specific range of elements, not just clear the entire array.
let arr = [1, 2, 3, 4, 5];
arr.splice(0, arr.length);
console.log(arr); // []
  1. Using pop() or shift() repeatedly, less efficient for clearing the entire array, but can be useful in specific scenarios where you need to process elements from head or tail while removing them.
let arr = [1, 2, 3, 4, 5];
while (arr.length > 0) {
  arr.pop();
  // or arr.shift()
}
console.log(arr); // []