1. Introduction

In this short article, we’re going to look at how to empty an array in JavaScript.

2. Empty An Array In JavaScript

2.1. Set The Length Of The Array To Zero

One of the main solutions to empty an array in JavaScript is to set the length of the array to zero, for example:

Setting the length of the array to zero will clear the array. By using this way, we can still keep the original array to which any other references will be updated too.

2.2. Set The Array To A New Empty Array

A quick way to empty an array in JavaScript is to set the array to a new empty one, for example:

2.3. Use The splice() Method

Another option for us to empty an array in JavaScript is to leverage the splice() method, for example:

The splice() method changes the contents of an array by removing existing elements and/or adding new elements. Let’s have a quick look at its syntax:

Parameters

  • start

Index at which to start changing the array (with origin 0).

  • deleteCount

An integer indicating the number of old array elements to remove.

  • item1, item2, … (Optional)

The elements to add to the array, beginning at the start index.

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

Let’s get back to the command to empty the above array of fruits:

We can see that the start parameter is 0 and the deleteCount parameter is the length of the array, therefore, the splice() method will clear all elements of the array.

2.4. Empty An Array Manually Using The pop() Method

Another option to empty an array in JavaScript is to manually remove all the elements of the array by using the pop() method, for example:

3. Conclusions

The tutorial has illustrated how to empty an array in JavaScript by different ways, and we can see that setting the array to a new empty array is the quickest way while the last way, using the pop() method to remove each element of the array is the slowest way.

The source code presented in the tutorial is available on my Github project. You can easily check it out and run it with jest or mocha.

Here are other related articles for your references:

JavaScript Tutorials

Check If A String Contains Substring In JavaScript

How To Convert String To Number In JavaScript

Loop Through Object Properties In JavaScript

0 0 vote
Article Rating