Use $.isArray() to check whether an object is an array. Then you can check the truthness of the length property to see whether it is empty.
if( !$.isArray(siteArray) || !siteArray.length ) {
//handler either not an array or empty array
}
Answer from Arun P Johny on Stack OverflowUse $.isArray() to check whether an object is an array. Then you can check the truthness of the length property to see whether it is empty.
if( !$.isArray(siteArray) || !siteArray.length ) {
//handler either not an array or empty array
}
Two empty arrays are not the same as one another, for they are not the same object.
var a = [];
if (a === []){
// This will never execute
}
Use if (siteArray.length==0) to see if an array is empty, or more simply if (!siteArray.length)
function isArrayEmpty(array) {
return array.filter(function(el) {
return !jQuery.isEmptyObject(el);
}).length === 0;
}
jsFiddle Demo
Passes all of your tests.
A pure JavaScript solution would be to replace !jQuery.isEmptyObject(el) with Object.keys(el).length !== 0
Edit: Using Array.prototype.every
function isArrayEmpty(array) {
return array.every(function(el) {
return jQuery.isEmptyObject(el);
});
}
For those playing at home, a non jQuery solution:
var test2 = [{a: 1},{},{}] ; //This is empty
function isEmpty(val) {
var len = val.length,
i;
if (len > 0) {
for (i = 0; i < len; ++i) {
if (!emptyObject(val[i])) {
return false;
}
}
}
return true;
}
function emptyObject(o) {
for (var key in o) {
if (o.hasOwnProperty(key)) {
return false;
}
}
return true;
}
console.log(isEmpty(test2));
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
}
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
You can use Object.keys() method to return all property names and check it's length:
Object.keys(myarray[0]).length === 0;
It depends on what you mean by "empty."
If you mean an object with no properties
If you mean you're getting:
[{}]
...then madox2's answer is a good way to check. Alternatively, you might have a function to do it that you can reuse:
function isEmptyObject(obj) {
for (const key in obj) {
if (Object.hasOwn(obj, key)) { // Remove this if you want to check for
// enumerable inherited properties
return false;
}
}
return true;
}
(Object.hasOwn was added in ES2022, but is easily polyfilled.)
If you mean [null] or similar
If you want to check specifically for undefined (note the === rather than ==) (but you won't get undefined from JSON):
if (myarray[0] === undefined)
Or specifically for null (note the === rather than ==):
if (myarray[0] === null)
Or for either of those (note the == rather than ===):
if (myarray[0] == null)
Or for any falsy value (0, "", NaN, null, undefined, or of course, false):
if (!myarray[0])
Below code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.
// works for any Object Including JSON(key value pair) or Array.
// var arr = [];
// var jsonObj = {};
if (jQuery.isEmptyObject(anyObjectIncludingJSON))
{
console.log("Empty Object");
}
Just test if the array is empty.
$.getJSON(url,function(json){
if ( json.length == 0 ) {
console.log("NO DATA!")
}
});
You don't have to parse the obj. It's already an object.
remove this line
obj = JSON.parse(obj);
As others have suggested, it appears you don't have a need what whatsoever for
obj = JSON.parse(obj);
Finally to check emptiness of an array is easy, in your case, do this:
r.innerHTML = !obj.data.length;
or
r.innerHTML = obj.data.length === 0;
But if you really have a need to define a function for this purpose, then the following should be enough:
function isEmpty(a) {
return a && !a.length;
}