JavaScript : 5 Ways to Empty an Array


In this short tutorial we will learn about different ways to empty and array in JavaScript.

JavaScript provides us some methods like pop(), shift() and splice() that we can use to clear/empty an array.

Lets us see 5 different ways along with examples.

Method 1 : Assigning an Empty Array.

This is one of the simple and easy way to clear an array. We just have to assign the array variable an empty array.

Example:

let a = [1, 2, 3]
a = []

console.log(a) // output: []

Using this method, make sure that you do not have any reference to the original array.

Example:

let b = [1, 2, 3]
let a = b
a = []

console.log(a) // []
console.log(b) // [1, 2, 3]

As you can see, the original array remains the same.

Method 2 : Setting array length to zero

We generally use the length property to check how many items we have in the array. However when we set array's length to zero (0), all the items in the array automatically gets deleted.

Example:

let a = [1, 2, 3]
a.length = 0

console.log(a) // []

Method 3 : Using splice() to Empty an Array

The splice() method is use to add or remove items to or from an array. This method modifies the original array.

Syntax:

Array.splice(start, delCount, item1, item2, itemN)

start : From which position to add or remove item in the array.

delCount : The number of items to be deleted from the start position.

item1,item2,itemN : This is optional argument and it is use to add items at specific position in the array.

Lets us see an example:

let a = [1, 2, 3]
a.splice(0, a.length)

console.log(a) // []

In the above example, we have used a.length because it gives us the total number of item present in the array. And since we want to delete all the items from position 0 we have used splice(0, a.length) .

Method 4 : Using pop() to clear an array

The pop() is use to remove the last element from an array. To empty the whole array we can use pop() in a while loop in JavaScript.

Example:

const arr = [1, 2, 3]

while(arr.length > 0) {
  arr.pop()
}

console.log(arr) // []

The while loop will keep on running till the array's length is less or equal to zero.

Method 5 : Using shift() to clear an Array

The shift() method is use to remove the first item from an array. And we can use a while loop to remove all the items from the array.

Example:

const arr = [1, 2, 3]

while(arr.length > 0) {
  arr.shift()
}

console.log(arr) // []

Related Topics:

How To Remove Object From Array In JavaScript?

Quick Way To Reverse An Array In JavaScript

How To Remove A Specific Item From An Array In JavaScript ?

Remove First And Last Element From An Array In JavaScript

How To Insert An Item Into An Array At A Specific Index In JavaScript?

Ways To Loop An Array In JavaScript | Quick Ways


💾 Recommended Articles