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
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
}
🌐
DEV Community
dev.to › kontent_ai › how-to-check-if-array-is-empty-in-typescript-573k
How To Check If Array Is Empty In TypeScript - DEV Community
December 8, 2021 - Checking the array length in the if condition could be shortened to just !blogPost.length which will evaluate to true if the array is empty since 0 is falsy and gets inverted and coerced into a boolean.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › check-if-an-array-is-empty-or-not-in-typescript
Check if an Array is Empty or not in TypeScript - GeeksforGeeks
August 5, 2025 - This approach uses the length property which is a built-in property in Typescript. This property returns the number of elements in the array. myArray.length; Example: The below example uses the length property to check whether the passed array ...
🌐
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 JavaScr... | Ash Allen Design
January 8, 2024 - We should always be sure that we're interacting with an array before we attempt to read the length property. If you're using TypeScript, this shouldn't be a problem since you'll be able to define the type of the variable you're interacting with. However, if you're using vanilla JavaScript, you'll need to be a bit more careful and explicitly check ...
🌐
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

🌐
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
🌐
Matiashernandez
matiashernandez.dev › blog › post › typescript-how-to-create-a-non-empty-array-type
Typescript: How to create a non empty array Type
So whenever you require, for example, a function parameter to be an array that cannot be empty, you can use NonEmptyArray . The only drawback is that you will now require a “type guard” function since simply checking if the length property of an array is not 0 will not transform it to type NonEmptyArray
🌐
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 - Employing Array.prototype.join: Convert the array to a string using a delimiter and check if the resulting string is empty.
🌐
Reddit
reddit.com › r/typescript › is there a way to guard against empty arrays?
r/typescript on Reddit: Is there a way to guard against empty arrays?
January 20, 2021 -

Suppose I have these types

interface Person {
  name: string;
  age?: number;
}

type People = Person[];

I then want to use the array type like so

const people: People = [];

const firstPerson = people[0];

console.log(firstPerson.name);

TypeScript doesn't complain about this usage because it doesn't have a clue about the size of arrays at compile time (I'm assuming) and thus it sees "sure, an array of Person, the first element must be a Person and not undefined, seems legit". Obviously though, when the JS is executed, this will fail with the error Cannot read property "name" of undefined.

I've come up with a rudimentary type guard, but that feels a bit cumbersome to use everywhere and doesn't catch everything:

const arePeople = (array: People): array is People => {
  return Array.isArray(array) && array.length > 0 && array[0].name != null
}

So the question is, is there a way to tell TypeScript that an array has at least 1 item of the correct type, other than using that typeguard

Find elsewhere
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
🌐
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.
🌐
Flexiple
flexiple.com › javascript › check-if-array-empty-javascript
How to check if an array is empty using Javascript? - Flexiple
Having confirmed that the variable is an array, now we can check the length of the array using the Array.length property. If the length of the object is 0, then the array is considered to be empty and the function will return TRUE.
🌐
Medium
medium.com › programming-essentials › how-to-know-if-an-array-is-not-empty-in-javascript-1aefa54ee138
How to Know If an Array is Not Empty in JavaScript | by Cristian Salcescu | Frontend Essentials | Medium
April 29, 2021 - const arr = [1, 2, 3];if(arr.length) { console.log('not empty'); } If the variable storing the array can be null or undefined then we need to check if the array actually exists before accessing its length property.
🌐
DevGenius
blog.devgenius.io › typescript-when-to-use-null-undefined-or-empty-array-d45244ffc565
Typescript: when to use null, undefined or empty array? | by Aleksei Jegorov | Dev Genius
May 13, 2022 - Check for empty array: first we check for undefined, second can check for property. ... This operator says to the compiler that the field isn’t null or undefined but it’s defined. type Tariff = { name: string; };let tariff: Tariff; tariff ...
🌐
GitConnected
levelup.gitconnected.com › 5-ways-to-check-if-a-javascript-array-is-empty-77eff962a232
5 ways to check if a Javascript Array is empty | by Miroslav Šlapka | Level Up Coding
March 28, 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.
🌐
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 ...
🌐
Board Infinity
boardinfinity.com › blog › how-to-quickly-check-if-an-array-is-empty-or-not-in-javascript
Check if Array is Empty or Not-Javascript | Board Infinity
July 9, 2023 - The array.length property can be used to determine whether the array is empty. The array's element count is returned by this attribute. The integer evaluates to true if it is bigger than 0. When used with the AND(&&) operator, this method and ...
🌐
Latenode
community.latenode.com › other questions › javascript
How can I verify if an array is empty or undefined?
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 }
🌐
GeeksforGeeks
geeksforgeeks.org › check-if-an-array-is-empty-or-not-in-javascript
Check if an array is empty or not in JavaScript | GeeksforGeeks
November 9, 2024 - The length property can be used to get the length of the given array if it returns 0 then the length of the array is 0 means the given array is empty else the array have the elements.