How do I empty an array in JavaScript?

javascript create empty array
javascript check empty array
angular 4 clear array
how to clear an array c++
clear array java
javascript array
javascript add to array
empty array php

Is there a way to empty an array and if so possibly with .remove()?

For instance,

A = [1,2,3,4];

How can I empty that?


Ways to clear an existing array A:

Method 1

(this was my original answer to the question)

A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

This is also the fastest solution.

This code sample shows the issue you can encounter when using this method:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Method 2 (as suggested by Matthew Crumley)

A.length = 0

This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

Method 3 (as suggested by Anthony)

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

Method 4 (as suggested by tanguy_k)

while(A.length > 0) {
    A.pop();
}

This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.

Performance

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.

As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.

The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).


This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.

How do I empty an array in JavaScript?, Ways to clear an existing array A : Method 1. (this was my original answer to the question) A = [];. This code will set the variable A to a new empty array. This is  In other words, if you have two references to the same array ( a = [1,2,3]; a2 = a; ), and you delete the array’s contents using list.length = 0, both references (a and a2) will now point to the same empty array. (So don’t use this technique if you don’t want a2 to hold an empty array!)


If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

A.length = 0;

Two ways to empty an array, You define an array and want to empty its contents. Usually, you would do it like js-javascript-logo Submit your tip define Array var list = [1, 2, 3, 4]; function empty() { //empty your array list = []; } empty();. But there is another  Use splice() method, set length to zero, using pop() method and set array to new empty array are 4 ways to empty an array in JavaScript. To clear an array Skip to content Fellow Tuts


Here the fastest working implementation while keeping the same array ("mutable"):

function clearArray(array) {
  while (array.length) {
    array.pop();
  }
}

FYI it cannot be simplified to while (array.pop()): the tests will fail.

FYI Map and Set define clear(), it would have seem logical to have clear() for Array too.

TypeScript version:

function clearArray<T>(array: T[]) {
  while (array.length) {
    array.pop();
  }
}

The corresponding tests:

describe('clearArray()', () => {
  test('clear regular array', () => {
    const array = [1, 2, 3, 4, 5];
    clearArray(array);
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });

  test('clear array that contains undefined and null', () => {
    const array = [1, undefined, 3, null, 5];
    clearArray(array);
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });
});

Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152

In Javascript how to empty an array, There are multiple ways to clear/empty an array in JavaScript. You need to use them based on the context. Let us look at each of them. Assume  Ways to clear an existing array A: Method 1 (this was my original answer to the question) A = []; This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged.


A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:

A.splice(0, A.length);

How to Clear an Array in JavaScript, In JavaScript, arrays can be declared literally or they can be initialized using the Array constructor function. But wait… What if you want to empty  Second, you can set the array’s length to zero. Replace an array with an empty array The first way of clearing myArray works like this: myArray = []; Depending on where the old value of myArray came from, this is the safer alternative, because you don’t change that value. You do create extra garbage: you don’t reuse the existing array, you create a new one.


How to empty an array in JavaScript?, There are many ways to empty an array in JavaScript some of them are discussed below: Method 1: Setting to new Array: This method sets the array variable to  JavaScript arrays are used to store multiple values in a single variable. An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: However, what if you want to loop through the cars and find a specific one?


Check if an array is empty or not in JavaScript, The array can be checked if it is empty by using the array.length property. This property returns the number of elements in the array. If the number is greater than 0,  Emptying an array is a common JavaScript task but too often I see the task performed in the incorrect way. Many times developers will create a new array: myArray = []; // bad That isn’t the optimal way to get a fresh array; to truncate an array, and thus empty it, you should set the …


Two ways of clearing an array in JavaScript, Let's say we want to clear the array in the following variable myArray: var myArray = [ elem0, elem1, ]; First, you can replace the current value  The most "empty" value I can think of is undefined, but JSON can't give you an array with an undefined entry, as it doesn't have that concept. – T.J. Crowder Mar 24 '16 at 17:26 FYI, myarray[0]=='empty' tests whether the first array element is the string 'empty' .


How to empty a JavaScript array, Given a JavaScript array, see how to clear it and empty all its elements. Published Dec 03, 2018. Sponsor. There are various ways to empty a JavaScript​  {} and [] Use {} instead of new Object (). Use [] instead of new Array (). Use arrays when the member names would be sequential integers. Use objects when the member names are arbitrary strings or names. source – ilgaar Jun 3 '17 at 11:49. new Object () and {} are not quite empty objects, they are objects that have the Object.prototype. You