5 Ways to Empty an Array in JavaScript

JavaScript

In this tutorial, we will explain how to empty an array in JavaScript. There is many way to empty an array but we will explain 5 ways to empty an array in JavaScript. In previous article we have explained how to remove duplicates from an array in JavaScript. The 5 ways to empty an array are as folows.

  1. Assign new empty array
  2. Length property
  3. Splice() method
  4. Pop() method
  5. Shift() method

Using new empty array

In this way we will assign new empty array to existing array. Like as below example.

let array = [1, 2, 3, 4, 5]

array = []

console.log(array) // Output - []

Using length property

In this way we will set the length zero of an array. Using length property we can find the the length of an array in JavaScript. Like as below example.

let array = [1, 2, 3, 4, 5]

array.length = 0

console.log(array) // Output - []

Using splice() method

In this way we will use splice method. Basically splice() method is used to add or remove item from an array in JavaScript. It returns removed items from an array. Like as below example.

let array = [1, 2, 3, 4, 5]

array.splice(0, array.length)

console.log(array) // Output - []

In this example we have used splice method to empty an array. In this method we have set the start position zero and removed item is equal o length of an array.

Using pop() method

In this way we will use pop() method to empty an array in JavaScript. Basically pop() method is used to remove the last element from an array in JavaScript. Like as below example.

let array = [1, 2, 3, 4, 5]

while (array.length > 0) {

    array.pop()

}

OR

for (var i = array.length; i > 0; i--) {

    array.pop();

}

console.log(array) // Output - []

Using shift() method

In this way we will use shift() method to empty an array in JavaScript. Basically shift() method is used to remove the first element from an array in JavaScript. Like as below example.

let array = [1, 2, 3, 4, 5]

while (array.length > 0) {

    array.shift()

}

OR

for (var i = array.length; i > 0; i--) {

    array.shift();

}

console.log(array) // Output - []

So in this article we have discussed about how to empty an array in JavaScript. In this article we have explained 5 ways to empty an array in JavaScript. Using this tutorial anyone can easily understand way to empty an array in JavaScript.

If you want to improve this tutorial or find anything wrong/incorrect then please leave a message using below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *

4 − 1 =