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
}
Answer from Robby Cornelissen on Stack Overflow
🌐
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
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
}
Top answer
1 of 16
706
if (typeof image_array !== 'undefined' && image_array.length > 0) {
    // the array is defined and has at least one element
}

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

<?php echo "var image_array = ".json_encode($images);?>
// add var  ^^^ here

And then make sure you never accidently redeclare that variable later:

else {
    ...
    image_array = []; // no var here
}
2 of 16
355

To check if an array is either empty or not

A modern way, ES5+:

if (Array.isArray(array) && array.length) {
    // array exists and is not empty
}

An old-school way:

typeof array != "undefined"
    && array != null
    && array.length != null
    && array.length > 0

A compact way:

if (typeof array != "undefined" && array != null && array.length != null && array.length > 0) {
    // array exists and is not empty
}

A CoffeeScript way:

if array?.length > 0

Why?

Case Undefined
Undefined variable is a variable that you haven't assigned anything to it yet.

let array = new Array();     // "array" !== "array"
typeof array == "undefined"; // => true

Case Null
Generally speaking, null is state of lacking a value. For example a variable is null when you missed or failed to retrieve some data.

array = searchData();  // can't find anything
array == null;         // => true

Case Not an Array
Javascript has a dynamic type system. This means we can't guarantee what type of object a variable holds. There is a chance that we're not talking to an instance of Array.

supposedToBeArray =  new SomeObject();
typeof supposedToBeArray.length;       // => "undefined"

array = new Array();
typeof array.length;                   // => "number"

Case Empty Array
Now since we tested all other possibilities, we're talking to an instance of Array. In order to make sure it's not empty, we ask about number of elements it's holding, and making sure it has more than zero elements.

firstArray = [];
firstArray.length > 0;  // => false

secondArray = [1,2,3];
secondArray.length > 0; // => true
🌐
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 - So if the array is empty, the length property will return 0. We can then check against this integer to determine whether the array is empty or not. If the array is empty, the expression will return true like so: ... There are some caveats to ...
🌐
Reddit
reddit.com › r/typescript › how to access a possibly empty array by index?
r/typescript on Reddit: How to access a possibly empty array by index?
March 19, 2024 -

this is my situation

let matches : string[] | null = topic.match(this._DEVICE_TOPIC_REGEXP);
console.log("handleNewMeasure, topic", topic, "matches", matches);
if (typeof matches === undefined ) {
return;
}
let device_id = matches[1];

I cannot go on because last line warns me that it could be empty

🌐
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 - To open up your console in Chrome, you can click Inpsect -> Console. First, create an array with no items in it. Next, let's use the logical "not" operator, along with our .length property, to test if the array is empty or not.
🌐
Latenode
community.latenode.com › other questions › javascript
How can I verify if an array is empty or undefined? - JavaScript - Latenode Official Community
October 10, 2024 - What is an efficient method to determine if an array is either empty or undefined? Is this a viable way to check this? if (!array || array.length === 0) { // array is empty or doesn't exist }
🌐
Flexiple
flexiple.com › javascript › check-if-array-empty-javascript
How to check if an array is empty using Javascript? - Flexiple
We can see here that fruitArr is an array and hence passes into the second condition to check if the length of the array is empty. Since the array has 3 elements it is not empty and therefore the function returns False. In the second case, arrTwo, it is again an array and so passes into the second condition. Here, since the array is empty, the function returns True.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › check-if-an-array-is-empty-or-not-in-javascript
Check if an array is empty or not in JavaScript - GeeksforGeeks
July 11, 2025 - let a = []; if (a.length == 0) { console.log("Empty"); } else { console.log("Not Empty"); } The Array.isArray() method checks whether the given variable consist of array or not. if it returns true then is checks for the length and prints the ...
Find elsewhere
🌐
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 guide promises to enlighten those new to the programming world and provide valuable insights for seasoned developers. ... The most straightforward way to check if an array is empty is by using the length property.
🌐
Reddit
reddit.com › r/frontend › javascript wtf: why does every() return true for empty arrays? - human who codes
r/Frontend on Reddit: JavaScript WTF: Why does every() return true for empty arrays? - Human Who Codes
November 14, 2023 - The article discusses JavaScript's every() method and its behavior with empty arrays. Normally, one would expect every() to return true only if all elements in an array satisfy a certain condition.
🌐
GoLinuxCloud
golinuxcloud.com › home › javascript › 6 methods to check if array is empty in javascript
6 Methods to check if Array is Empty in JavaScript | GoLinuxCloud
April 15, 2024 - It’s worth mentioning that though every() method is not commonly known for checking emptiness but technically this method can find out whether or not an array is empty by testing every element against certain condition since there are no any ...
🌐
Elightwalk
elightwalk.com › home
Easy Ways to Check If an Array is Empty in JavaScript
July 31, 2025 - Even if you use === [] to check if an empty array is empty, the result is false: ... This is because arrays in JavaScript are objects.
Price   $
Address   611, Shivalik Square, near Adani CNG pump, Ramapir Thekra, Nava Vadaj, 380027, Ahmedabad
🌐
Reddit
reddit.com › r/learnprogramming › how do you remove an empty array within an array? js
r/learnprogramming on Reddit: How do you remove an empty array within an array? JS
November 19, 2022 -

I have some testing criteria and I've hit everything EXCEPT I can't filter out a fucking empty array within the array.

Array = [7, 10, 'hi', 'seven', null, [] ];

I've filtered everything and able to return only the even length strings but I can't get rid of the empty []

Searching Google keeps coming up short also with how to do it but I'm sure it's there, I just can't find it!

This is in JavaScript, thanks.

🌐
Reddit
reddit.com › r/godot › tell if variable contains an empty array?
r/godot on Reddit: Tell if variable contains an empty array?
September 9, 2022 -

I've been using not someVar as a check for null on variables. It seems, however, that empty arrays will also return true for that (not [] == true) which throws a wrench in my check if I'm dealing with arrays.

What would be the correct method to test that the value is an array and not null?

Thanks.

🌐
Mairo
blog.mairo.eu › 5-ways-to-check-if-javascript-array-is-empty
5 ways to check if Javascript Array is empty
March 26, 2022 - Speaking about the operators, I'd like to mention also the Nullish coalescing operator (??). Our array contains also an object, so we could check its property. let myArray = [1, 245, 'apple', { type: 'fruit' }] myArray?.[3]?.type ?? 'No type property' // 'fruit' We get whatever we evaluate on the left side if it's true, otherwise we get what is on the right side of ??. It depends on what you really need, but here's another way. Logical not operator negates the values. The following would return true in case myArray is empty, that is [], or undefined or null.
🌐
Medium
frontendinterviewquestions.medium.com › how-to-check-if-an-array-is-empty-in-javascript-778c7b727f68
How to Check if an Array is Empty in JavaScript? | by Pravin M | Medium
August 10, 2024 - The simplest and most common way to check if an array is empty is by using the length property. The length property returns the number of elements in the array.
🌐
Quora
quora.com › How-do-you-check-if-an-array-is-empty-in-JavaScript
How to check if an array is empty in JavaScript - Quora
Answer (1 of 9): To safely test if the array referenced by variable “array” isn’t empty: [code]if (array && array.length) { // not empty } else { // empty } [/code]Note that if “array” is assigned to some other object that isn’t an array, the code will still execute the “else” part.