How to Empty an Array in Javascript?

javascript

There are multiple ways to empty an array in JavaScript:

  1. Setting the length property of the array to zero

You can set the length property of the array to zero to delete all the elements inside it.

Example:

let arr = [1, 2, 3, 4];

arr.length = 0;

console.log(arr); // []
  1. Using the splice() method

The splice() method can be used to remove elements from an array. You can use it to remove all the elements of an array.

Example:

let arr = [1, 2, 3, 4];

arr.splice(0, arr.length);

console.log(arr); // []
  1. Using the pop() method in a loop

You can use the pop() method in a loop until all the elements are removed from the array.

Example:

let arr = [1, 2, 3, 4];

while (arr.length) {
  arr.pop();
}

console.log(arr); // []
  1. Using the shift() method in a loop

You can use the shift() method in a loop until all the elements are removed from the array.

Example:

let arr = [1, 2, 3, 4];

while (arr.length) {
  arr.shift();
}

console.log(arr); // []

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?