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
1550

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
}
๐ŸŒ
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 }
๐ŸŒ
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 (Array.isArray(a) && a.length === 0) { console.log("Empty"); } else { console.log("Not Empty"); }
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
354

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 - 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 !
๐ŸŒ
Tech Solution Stuff
techsolutionstuff.com โ€บ post โ€บ how-to-check-array-is-empty-or-null-in-javascript
How To Check Array Is Empty Or Null In Javascript
April 21, 2024 - This method is a reliable way to determine whether the array is empty or contains elements. <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script> <script type="text/javascript"> var Array1 = [1, 2, 3]; var Array2 = []; console.log(jQuery.isEmptyObject(Array1)); // returns false console.log(jQuery.isEmptyObject(Array2)); // returns true </script> Checking with the condition if an array is not undefined
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ how to check for null, undefined, or empty values in javascript
How to check for null, undefined, or empty values in JavaScript - LogRocket Blog
February 14, 2025 - Learn how to write a null check function in JavaScript and explore the differences between the null and undefined attributes.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ check-if-the-array-is-empty-or-null-or-undefined-in-javascript
Check if the array is empty or null, or undefined in JavaScript - javatpoint
Check if the array is empty or null, or undefined in JavaScript with javascript tutorial, introduction, javascript oops, application of javascript, loop, variable, objects, map, typedarray etc.
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 - Detecting array emptiness by trying to access an undefined property: This uses the fact that accessing an index that doesnโ€™t exist in an array returns undefined.
๐ŸŒ
ItSolutionstuff
itsolutionstuff.com โ€บ post โ€บ how-to-check-if-array-is-empty-or-null-or-undefined-in-javascriptexample.html
How to Check Array Is Empty Or Null In Javascript? - ItSolutionstuff.com
July 4, 2023 - If need for jquery check if array is empty or undefined then i will help you. you can easily check if array is empty or not in javascript. we will use simple if condition and length of array with checking. so we can easily check if array is empty null undefined in javascript.
๐ŸŒ
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
๐ŸŒ
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 - Next, let's use the logical "not" operator, along with our .length property, to test if the array is empty or not. If we had not used the "not" operator, arr.length would have returned 0. With the operator added, it will return true if its operand is false. Because arr.length is 0, or false, it returns true. Let's use this with an if statement, and print out a message if our array is empty.
๐ŸŒ
Flexiple
flexiple.com โ€บ javascript โ€บ check-if-array-empty-javascript
How to check if an array is empty using Javascript? - Flexiple
The Array.isArray() method is a sure shot method to check if a variable is an array or not and it automatically eliminates the cases of null and undefined without writing an additional script to check for it.
Top answer
1 of 5
193

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

  1. $(this) is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).length if you need to, but that is not necessary here because the .each() loop wouldn't run if there were no items so $(this) inside your .each() loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with [] rather than new Array().
  4. if (value) when value is expected to be a string will both protect from value == null, value == undefined and value == "" so you don't have to do if (value && (value != "")). You can just do: if (value) to check for all three empty conditions.
  5. if (album_text.length === 0) will tell you if the array is empty as long as it is a valid, initialized array (which it is here).

What are you trying to do with this selector $("input[name='album_text[]']")?

2 of 5
86

User JQuery is EmptyObject to check whether array is contains elements or not.

var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true
๐ŸŒ
ScratchCode
scratchcode.io โ€บ home โ€บ check if array is empty or undefined in javascript
Check If Array Is Empty Or Undefined In JavaScript | Scratch Code
December 23, 2020 - So letโ€™s check an array is empty or not. This method has one drawback. If you pass any non-empty string then it will pass the test which is wrong, so for that we have to use Method 2 but to understand Method 2, you should try & test Method 1. <script type="text/javascript"> let devices = [ 'keyboard', 'laptop', 'desktop', 'speakers', 'mouse' ]; // let devices = [ ]; // Try uncommenting this for testing if ( typeof devices !== 'undefined' &&amp; devices.length > 0 ) { alert('array is not empty'); } else { alert('array is empty'); } </script>
๐ŸŒ
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 - 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. ... How do we really know if we work with the array though? The length property exists also on the string.
๐ŸŒ
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.isArray() method can be used to determine whether an array is actually there and whether it exists. If the Object supplied as a parameter is an array, this function returns true.
Top answer
1 of 16
5789

You can just check if the variable has a truthy value or not. That means

if (value) {
    // do something..
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if (typeof foo !== 'undefined') {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

2 of 16
457

This question has two interpretations:

Check if the variable has a value
Check if the variable has a truthy value

The following answers both.

In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:

 โ•ญโ”€ nullish โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ•ญโ”€ not nullish โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”
โ”‚ undefined โ”‚ null โ”‚ false โ”‚ 0 โ”‚ "" โ”‚ ... โ”‚ true โ”‚ 1 โ”‚ "hello" โ”‚ ... โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”˜
 โ•ฐโ”€ falsy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€ truthy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Check if value is nullish (undefined or null)

Use one of the following depending on your coding style:

if (value == null)                         { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined)                    { /* value is nullish */ }
if ((value ?? null) === null)              { /* value is nullish */ }

Notes:

  • The == operator works because it has a special case for null vs undefined comparison
  • The === operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately
  • The first and third examples work identically, however the third one is rarely seen in production code
  • The fourth example uses nullish coalescing operator to change nullish values to null for straight forward comparison

Check if value is not nullish

if (value != null)                         { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined)                    { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null)              { /* value is not nullish, although it could be falsy */ }

Check if value is falsy

Use the ! operator:

if (!value) { /* value is falsy */ }

Check if value is truthy

if (value) { /* value is truthy */ }

Data validation

The nullish, falsy and truthy checks cannot be used for data validation on their own. For example, 0 (falsy) is valid age of a person and -1 (truthy) is not. Additional logic needs to be added on case-by-case basis. Some examples:

/*
 * check if value is greater than/equal to 0
 * note that we cannot use truthy check here because 0 must be allowed
 */
[null, -1, 0, 1].forEach(num => {
  if (num != null && num >= 0) {
    console.log("%o is not nullish and greater than/equal to 0", num);
  } else {
    console.log("%o is bad", num);
  }
});

/*
 * check if value is not empty-or-whitespace string
 */
[null, "", " ", "hello"].forEach(str => {
  if (str && /\S/.test(str)) {
    console.log("%o is truthy and has non-whitespace characters", str);
  } else {
    console.log("%o is bad", str);
  }
});

/*
 * check if value is not an empty array
 * check for truthy before checking the length property
 */
[null, [], [1]].forEach(arr => {
  if (arr && arr.length) {
    console.log("%o is truthy and has one or more items", arr);
  } else {
    console.log("%o is bad", arr);
  }
});

/*
 * check if value is not an empty array
 * using optional chaining operator to make sure that the value is not nullish
 */
[null, [], [1]].forEach(arr => {
  if (arr?.length) {
    console.log("%o is not nullish and has one or more items", arr);
  } else {
    console.log("%o is bad", arr);
  }
});