Languages
[Edit]
EN

JavaScript - how to empty array

3 points
Created by:
Dirask Community
5850

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

Below examples show four solutions on how to do that:

  1. By setting the array to a new empty array,
  2. By setting the array's length to 0,
  3. By using splice() method,
  4. By using while loop.

1. Setting the array to a new empty array

In this solution, we set the existing variable to a new, empty array. To see if the array has been cleared, we display the result.

Runnable example:

// ONLINE-RUNNER:browser;

var array = [1,2,3];
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.
To see if the array has been cleared, we display the result.

Runnable example:

// ONLINE-RUNNER:browser;

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

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.
To see if the array has been cleared, we display the result.

Runnable example:

// ONLINE-RUNNER:browser;

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

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

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

Click here to read more about splice() method.

4. Using while loop 

In this solution we use while loop to pop() every single item from an array.
To see if the array has been cleared, we display the result.

Runnable example:

// ONLINE-RUNNER:browser;

var array = [1,2,3];

while(array.length > 0) {   // <----------
    array.pop();
}

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