122

I would like to know how to check if an array is empty or null in jQuery. I tried array.length === 0 but it didn't work. It did not throw any error either.

This is the code:

var album_text = new Array();

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

else {
  // send data
}
JJD
  • 50,076
  • 60
  • 203
  • 339
input
  • 7,503
  • 25
  • 93
  • 150
  • 2
    The same way as in "normal JavaScript": http://stackoverflow.com/questions/2672380/how-do-i-check-if-a-javascript-array-value-is-empty-or-null – Julien Schmidt Aug 25 '11 at 23:08
  • 1
    @Julien, I tried all of those solutions listed in that thread before starting this thread. None of them worked somehow. – input Aug 25 '11 at 23:10
  • Can we get some more code for context? Surrounding JavaScript, HTML? Are you sure that `$("input[name='album_text[]']")` is actually returning elements? – Jon Adams Aug 25 '11 at 23:33
  • @JulienSchmidt: the question you linked to is about checking if an array *value* is empty, not the entire array. – Dan Dascalescu Jan 20 '17 at 20:57

5 Answers5

189

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[]']")?

JJD
  • 50,076
  • 60
  • 203
  • 339
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 5
    @MaciekSemik - see http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons. I always use strict equality (`===`) unless I specifically want to allow a type conversion. It's a good habit to get into. – jfriend00 Apr 13 '14 at 18:21
83

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
Praxis Ashelin
  • 5,137
  • 2
  • 20
  • 46
Mayank Raipure
  • 1,773
  • 15
  • 12
  • 3
    Much more reliable than checking the length, especially if your variable can also be an object (with objects, length do not work to check if empty). – gaborous Nov 20 '14 at 02:43
  • This is the more appropriate answer in my opinion. – earl3s Mar 31 '15 at 17:49
  • 5
    `isEmptyObject` always returns `false` if `Array.prototype` is extended, e.g. `Array.prototype.someFunction = function () {};` - even if the array is empty. Note that some frameworks (e.g. Ember.js) extend Array prototype by default. – jesenko May 11 '15 at 18:04
  • 4
    Be careful with `isEmptyObject`!For jQuery 1.8.3 `jQuery.isEmptyObject([])` returns `false`, but for jQuery 1.11.3 it returns `true`. Actually, [jQuery documentation](https://api.jquery.com/jQuery.isEmptyObject/) says **The argument should always be a plain JavaScript Object as other types of object (DOM elements, primitive strings/numbers, host objects) may not give consistent results across browsers.** Sorry, didn't see @rhinoxi 's answer. – Dmitry Vershinin Nov 16 '16 at 09:00
9

I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.

In the isEmptyObject doc, it mentions:

The argument should always be a plain JavaScript Object

which you can determine by $.isPlainObject. The return of $.isPlainObject([]) is false.

rhinoxi
  • 111
  • 2
  • 6
8

You should check for '' (empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0 will work just fine.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Please see the updated the code. I added this code `if( $(this).val() && $(this).val() != '') ` yet it does not work. – input Aug 25 '11 at 23:08
4
/*
  Basic Checking with undefined array for Jquery Array
*/
if (typeof myArray !== 'undefined' && myArray.length > 0) {
    console.log('myArray is not empty.');
}else{
    console.log('myArray is empty.');
}
Amit Geek
  • 51
  • 4