Check if an array is empty or exists Check if an array is empty or exists arrays arrays

Check if an array is empty or exists


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 anythingarray == 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;  // => falsesecondArray = [1,2,3];secondArray.length > 0; // => true


How about (ECMA 5.1):

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