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. 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.

Answer from Philippe Leybaert on Stack Overflow
Top answer
1 of 16
5711

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. 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.

2 of 16
2755

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;
🌐
VisuAlgo
visualgo.net › en › array
Array - VisuAlgo
When we say compact array, we mean an array that has no gap, i.e., if there are N items in the array (that has size M, where M ≥ N), then only index [0..N-1] are occupied and other indices [N..M-1] should remain empty.
Discussions

How to Clear an Array in JavaScript
This raises at least 2 questions: in what situation would you want to "clear" an array? why would you even consider anything but method 1 (myVar = [];)? More on reddit.com
🌐 r/javascript
42
0
July 30, 2023
javascript - How to check if array is empty or does not exist? - Stack Overflow
What's the best way to check if an array is empty or does not exist? Something like this? if(array.length More on stackoverflow.com
🌐 stackoverflow.com
TIL: You can empty an array by assigning 0 to length
The length property has special powers, basically by mandate of the standard. length also has to "spy" on all array accesses, so that it's always one more than the highest assigned index. For example: var a = []; a[99] = 1; console.log(a.length); // => 100 The array doesn't actually contain 100 items; the first 99 slots are empty. But still length is updated by the assignment, and not through the process of calling some method like a.push() which would be the normal way that you'd update a property if it was a class that you were writing in pure JS. More on reddit.com
🌐 r/javascript
14
1
September 22, 2016
JavaScript WTF: Why does every() return true for empty arrays?
Because every member of the array meets the condition. It's logical More on reddit.com
🌐 r/javascript
40
0
September 5, 2024
🌐
freeCodeCamp
freecodecamp.org › news › check-if-javascript-array-is-empty-or-not-with-length
How to Check if a JavaScript Array is Empty or Not with .length
October 5, 2020 - By Madison Kanna When you're programming in JavaScript, you might need to know how to check whether an array is empty or not. To check if an array is empty or not, you can use the .length property. The length property sets or returns the number ...
🌐
CoreUI
coreui.io › blog › how-to-check-if-an-array-is-empty-in-javascript
How to check if an array is empty in JavaScript? · CoreUI
July 2, 2024 - An astute question arises: why not rely solely on the length property to determine if an array is empty? The answer lies in JavaScript’s flexibility.
🌐
Just Academy
justacademy.co › blog-detail › how-to-check-empty-array-in-javascript
How to Check Empty Array in JavaScript
1 - The most common way to check if an array is empty in JavaScript is to use the `length` property.
Find elsewhere
🌐
Ash Allen Design
ashallendesign.co.uk › blog › how-to-check-if-an-array-is-empty-in-javascript
How to Check If an Array Is Empty in JavaScript
January 8, 2024 - If the array is empty, the expression will return true like so: ... There are some caveats to using this approach, and we'll cover them further down in this article. A similar approach to the previous one is to use the length property with the ! operator. The ! operator is the logical NOT operator, and since in JavaScript 0 is a falsy value, we can use the !
🌐
Altcademy
altcademy.com › blog › how-to-create-an-empty-array-in-javascript
How to create an empty array in JavaScript
August 24, 2023 - An empty array is an array that does not contain any elements. It's like a shopping list you haven't written anything on yet, or a bookshelf you've just bought and haven't put any books on.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › length
Array: length - JavaScript | MDN
When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values.
🌐
W3Schools
w3schools.com › jsref › jsref_array_new.asp
JavaScript new Array Method
❮ Previous JavaScript Array Reference Next ❯ · // Create an Array const cars = new Array(["Saab", "Volvo", "BMW"]); Try it Yourself » · More Examples Below ! The new Array() constructor creates an Array object. new Array(iterable) Array Tutorial · Array Const · Basic Array Methods · Array Search Methods · Array Sort Methods · Array Iteration Methods · Create an empty array and add values: // Create an Array const cars = new Array(); // Add Values to the Set cars.push("Saab"); cars.push("Volvo"); cars.push("BMW"); Try it Yourself » ·
🌐
Reddit
reddit.com › r/javascript › how to clear an array in javascript
r/javascript on Reddit: How to Clear an Array in JavaScript
July 30, 2023 - Because method 1 is a footgun, it doesn't empty the array, it creates a new one.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-empty-an-array-in-javascript
How to Empty an Array in JavaScript? - GeeksforGeeks
July 11, 2025 - We can directly assign an empty array literal to the variable, it will automatically remove all the elements and make the array empty.
Top answer
1 of 1
1553

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array does not exist or is empty
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ⇒ do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ⇒ do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ⇒ probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ⇒ do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ⇒ probably OK to process array
}
🌐
Favtutor
favtutor.com › articles › check-javascript-array-empty
Check if JavaScript Array is Empty or Not (with code)
January 22, 2024 - Let’s look at methods to check whether an array is empty or not: We can use the .length property to check if a JavaScript array is empty or not. It can check the length of the array specifies the number of elements that it contains.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › Array
Array() constructor - JavaScript | MDN
Arrays can be created using a constructor with a single number parameter. An array is created with its length property set to that number, and the array elements are empty slots.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
2 weeks ago - Methods that have special treatment for empty slots include the following: concat(), copyWithin(), every(), filter(), flat(), flatMap(), forEach(), indexOf(), lastIndexOf(), map(), reduce(), reduceRight(), reverse(), slice(), some(), sort(), and splice(). Iteration methods such as forEach don't ...
🌐
W3Schools
w3schools.com › jsref › jsref_filter.asp
JavaScript Array filter() Method
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
🌐
Designcise
designcise.com › web › tutorial › what-is-the-best-way-to-check-if-an-array-is-empty-or-not-In-javascript
Best Way to Check if a JavaScript Array is Empty - Designcise
February 7, 2021 - The best way to check if an array is empty in JavaScript is by using the Array.isArray() method (ES5+) and array's length property together like so: // ES5+ if (!Array.isArray(array) || !array.length) { // ... } Similarly, using else, or the ...