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;
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
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 ...
🌐
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 ...
🌐
Sentry
sentry.io › sentry answers › javascript › how do i empty an array in javascript?
How do I Empty an Array in JavaScript? | Sentry
If you use this method to empty an array, bear in mind that the empty array is newly created. If another variable or property references the array, that variable or property will still point to the original array, as can be seen in the code example below: ... let arr = [1, 2, 3, 4, 5]; const arr2 = arr; arr = []; console.log(arr); // [] console.log(arr2); // [1, 2, 3, 4, 5] In JavaScript, objects are assigned and copied by reference, not by value.
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
}
🌐
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
February 7, 2024 - This operation is crucial in various scenarios, such as enabling or disabling buttons based on user input or ensuring data integrity before processing. In this article, part of the “how to” series, we delve into the intricacies of checking for empty arrays in JavaScript. This guide promises ...
🌐
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.
🌐
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 !
Find elsewhere
🌐
Reddit
reddit.com › r/javascript › how to clear an array in javascript
r/javascript on Reddit: How to Clear an Array in JavaScript
July 29, 2023 - Because method 1 is a footgun, it doesn't empty the array, it creates a new one.
🌐
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 » ·
🌐
Quora
quora.com › How-do-you-declare-an-empty-array-in-JavaScript
How to declare an empty array in JavaScript - Quora
Answer (1 of 19): You have two main ways to go: simple declaration with square brackets. const myArray = [] Or instantiation of the Array Object using the constructor method: const myArray = new Array() The trendy kids favor the first way, nowadays, with the empty square brackets, but if you h...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Why does this return as an empty array? - JavaScript - The freeCodeCamp Forum
June 28, 2022 - I cannot find a logical reason why this code would continue to produce an empty array. Any ideas? **Your code so far** function copyMachine(arr, num) { let newArr = []; while (num >= 1) { let adder = [...arr]; newArr = newArr.splice(0, 0, adder); num--; } return newArr; } console.log(copyMachine([true, false, true], 2)); **Your browser information:** User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36 Challen...
🌐
Reddit
reddit.com › r/learnjavascript › !! vs ==0 when checking if array is empty
r/learnjavascript on Reddit: !! vs ==0 when checking if array is empty
June 30, 2024 -

I have an array in a function and I want the function to return true/false depending on if the array is empty (return true if not empty and vice versa)

I have narrowed down the condition to these 2 possible return statements. Which one is preferred?

return result.recordset.length == 0

return !!result.recordset.length
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Errors › Reduce_of_empty_array_with_no_initial_value
TypeError: Reduce of empty array with no initial value - JavaScript | MDN
const names = document.getElementsByClassName("names"); const nameList = Array.prototype.reduce.call( names, (acc, name) => `${acc}, ${name}`, ); These problems can be solved in two different ways. One way is to actually provide an initialValue as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation.
🌐
Code Like A Girl
code.likeagirl.io › create-an-array-of-empty-arrays-7ec77edea546
How to create an array of empty arrays | by Ai-Lyn Tang | Code Like A Girl
June 25, 2019 - Array.from makes an array out of this. The examples on the Mozilla developer documentation go through simpler use cases in my mind, so this also doesn’t quite make sense to me either. Namely why do I need Array.from at all? But I’ll accept it and move on for now.
🌐
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.
🌐
Flexiple
flexiple.com › javascript › check-if-array-empty-javascript
How to check if an array is empty using Javascript? - Flexiple
The answer is NO, because an array in JavaScript is an instance of the Array object and typeof would return the type object for it.
🌐
JavaScript Tutorial
javascripttutorial.net › home › 4 ways to empty an array in javascript
4 Ways to Empty an Array in JavaScript
January 31, 2020 - let a = [1,2,3];Code language: JavaScript (javascript) The following shows you several methods to make an array empty.
🌐
Medium
medium.com › @ryan_forrester_ › empty-arrays-in-javascript-how-to-guide-f8643da412c2
Empty Arrays in JavaScript (How to Guide) | by ryan | Medium
October 30, 2024 - This guide will provide you with a detailed understanding of how to create, check, and manipulate empty arrays in JavaScript, including practical examples.
🌐
DEV Community
dev.to › sanchithasr › 3-ways-to-empty-an-javascript-array-1lfm
3 ways to empty an Array in JavaScript - DEV Community
December 22, 2020 - Whoah, I never knew Array#length was settable! Setting it almost seems like an antipattern, because you'd expect it to be a read-only property, but it also looks to be the cleanest way to empty an array in-place (the splice version is even less intuitive).