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 resolve "SecurityError: Blocked a frame with origin from accessing a cross-origin frame" in javascript? javascript How to set the value of an input field in Javascript? javascript How to get the current URL using jQuery?