Languages
[Edit]
EN

JavaScript - how to empty array

3 points
Created by:
Elmer-Li
336

In this article, we would like to show you how to clear / empty an array in JavaScript.

Quick solution:

array.splice(0, array.length);

 

There are available following ways to clear the array:

  1. by setting the empty array as a variable value,
  2. by setting the array's length to 0,
  3. by using splice() method,
  4. by using pop() method in while loop.

 

1. Setting the empty array as a variable value

In this solution, we set the existing variable to a new empty array.

Runnable example:

// ONLINE-RUNNER:browser;

var array = [1,2,3];
array = []; // <---------- new empty array

console.log(array.length);  // 0

Note:
You should be careful using this method, because if you have referenced array from another variable or property, the original array will remain unchanged.

2. Setting the array's length to 0 

In this solution, we empty the existing array by setting its length to 0.

Runnable example:

// ONLINE-RUNNER:browser;

var array = [1,2,3];
array.length = 0; // <---------- array size reset that clears array

console.log(array.length);  // 0

3. Using splice() method 

In this solution we use splice() method to remove every item from index 0 to array.length.

Runnable example:

// ONLINE-RUNNER:browser;

var array = [1,2,3];
array.splice(0, array.length); // <---------- removes all items

console.log(array.length);  // 0

Note:
splice() method will return an array with all the removed items.

Click here to read more about splice() method.

4. Using pop() method in while loop 

In this solution we use while loop to pop() every single item from an array.

Runnable example:

// ONLINE-RUNNER:browser;

var array = [1,2,3];

while(array.length > 0) {
    array.pop(); // <---------- each iteration removes one item
}

console.log(array.length);  // 0

Note:
This solution is the slowest from all of the above. 

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join