555

When the page is loading for the first time, I need to check if there is an image in image_array and load the last image.

Otherwise, I disable the preview buttons, alert the user to push new image button and create an empty array to put the images;

The problem is that image_array in the else fires all time. If an array exists - it just overrides it, but alert doesn't work.

if(image_array.length > 0)
    $('#images').append('<img src="'+image_array[image_array.length-1]+'" class="images" id="1" />');
else{
    $('#prev_image').attr('disabled', 'true');
    $('#next_image').attr('disabled', 'true');
    alert('Please get new image');
    var image_array = [];
}

UPDATE Before loading html, I have something like this:

<?php if(count($images) != 0): ?>
<script type="text/javascript">
    <?php echo "image_array = ".json_encode($images);?>
</script>
<?php endif; ?>
Flip
  • 6,233
  • 7
  • 46
  • 75
user1564141
  • 5,911
  • 5
  • 21
  • 18

24 Answers24

678
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
}
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • 50
    Nope. This will blast when image_array is null. Murphy's law states that some day it will. – Marco Faustinelli Mar 20 '15 at 06:32
  • 11
    Isn't `image_array.length` enough? (without specifying `>0`) – mcont Apr 12 '15 at 12:56
  • Curious: Can you find any use case that would break using the answer of @JamesDrinkard? – tsemer Aug 24 '16 at 09:01
  • 20
    `if (image_array && image_array.length){ // array exists and has elements` – YeeHaw1234 Nov 04 '16 at 18:53
  • 1
    This fails for `let image_array = new Array(10);`. – Saket Kumar Nov 12 '20 at 00:30
  • ```Array.isArray(arr);``` enjoy – Hidayt Rahman Dec 02 '20 at 19:44
  • i faced situation that var test_array = new Array();, then started function and inside the function with typeof test_array get object, but if (typeof test_array !== 'undefined') { get false and with if (typeof test_array != 'undefined') { get true. So array exists, but with !== i get that as if does not exist. Finally problem was becaus of my negligance. I had html id with the same name as array name. That is why typeof !== did not work as expected. – Andris Aug 01 '22 at 04:42
338

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
Mike
  • 14,010
  • 29
  • 101
  • 161
Pooyan Khosravi
  • 4,861
  • 1
  • 19
  • 20
  • 8
    Please note that it is **not** sufficient to just check for `(typeof array != "undefined" && array.length > 0)` because if `array` is null we'll get `TypeError: Cannot read property 'length' of null`. – Pooyan Khosravi May 09 '14 at 20:56
  • Maybe change && with || – Sahar Ch. May 30 '14 at 13:42
  • `!(typeof array !== "undefined") || !(array.length > 0)`? Just tried it, got same error. Can you give us a full example of how to use `||`? – Pooyan Khosravi May 30 '14 at 16:12
  • I meant `(typeof array != "undefined" || array.length > 0)` – Sahar Ch. May 30 '14 at 23:24
  • Thanks for clarification. `(typeof array != "undefined" || array.length > 0)` returns `true` if `array = null`. `!(typeof array != "undefined" || array.length > 0)` returns `false` if `array = [1,2]`. Sorry for not understanding, but @Elsa can you provide a working example? Thanks in advance. – Pooyan Khosravi Jun 02 '14 at 20:50
  • If `array.length != null` is needed to be sure that what we have is an array, why can we then omit it when doing the compact way? – techfly Feb 07 '18 at 07:25
  • @Aenadon Both `undefined > 0` and `null > 0` evaluate to `false`; evaluation of an undefined property on a defined object returns `undefined`. This is a trick; we really shouldn't use tricks. I'm going to remove it. – Pooyan Khosravi Feb 12 '18 at 22:18
  • Re `.. && array.length)`. IMHO, while you *can* safely rely on JS's loose-typing, to convert a `0` integer to `false` and a `non-zero` integer to `true`, I consider it preferable, for readability in the future, to "say what you mean". I would do `.. && array.length > 0)`. – ToolmakerSteve Oct 12 '19 at 12:16
  • flawless answer! – Gaurav Jan 28 '22 at 09:06
78

How about (ECMA 5.1):

if(Array.isArray(image_array) && image_array.length){
  // array exists and is not empty
}
Queequeg
  • 947
  • 7
  • 11
  • 5
    Re `.. && image_array.length)`. IMHO, while you *can* safely rely on JS's loose-typing, to convert a `0` integer to `false` and a `non-zero` integer to `true`, I consider it preferable, for readability in the future, to "say what you mean". I would do `.. && image_array.length > 0)`. – ToolmakerSteve Oct 12 '19 at 12:17
71

This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.

if(arrayName && arrayName.length > 0){
    //do something.
}

or thanks to tsemer's comment I added a second version

if(arrayName && arrayName.length)

Then I made a test for the second condition, using Scratchpad in Firefox:

var array1;
var array2 = [];
var array3 = ["one", "two", "three"];
var array4 = null;

console.log(array1);
console.log(array2);
console.log(array3);
console.log(array4);

if (array1 && array1.length) {
  console.log("array1! has a value!");
}

if (array2 && array2.length) {
  console.log("array2! has a value!");
}

if (array3 && array3.length) {
  console.log("array3! has a value!");
}

if (array4 && array4.length) {
  console.log("array4! has a value!");
}

which also proves that if(array2 && array2.length) and if(array2 && array2.length > 0) are exactly doing the same

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
James Drinkard
  • 15,342
  • 16
  • 114
  • 137
  • 2
    Short and quick! It took me a while coming from C# to get used to if(obj) to check for null, but now I love it: if(obj) // null check; if(array && array.length) // array null or empty check; if(array && !array.length) // array exists, but empty check; if(str) // string not null and not empty. The only gotcha is don't use on numbers if zero is a valid number. – Rick Love Feb 27 '17 at 03:47
  • 1
    In Typescript there are nuances, as for `var arrayName = undefined; var isNotEmpty = arrayName && array.length > 0` type for isNotEmpty would not be boolean, it would be boolean|undefined. – Giedrius May 21 '19 at 08:54
59

optional chaining

As optional chaining proposal reached stage 4 and is getting wider support, there is a very elegant way to do this

if(image_array?.length){

  // image_array is defined and has at least one element

}
LonelyCpp
  • 2,533
  • 1
  • 17
  • 36
19

You should use:

  if (image_array !== undefined && image_array.length > 0)
Samson
  • 2,801
  • 7
  • 37
  • 55
10

If you want to test whether the image array variable had been defined you can do it like this

if(typeof image_array === 'undefined') {
    // it is not defined yet
} else if (image_array.length > 0) {
    // you have a greater than zero length array
}
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Not working https://dl.dropbox.com/u/14396564/screens/%D0%A1%D0%BD%D0%B8%D0%BC%D0%BE%D0%BA%20%D1%8D%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202012-07-31%20%D0%B2%2018.25.27.png – user1564141 Jul 31 '12 at 15:29
  • @user1564141 hard to tell where the function is being declared relative to your image_array being set. You might be having a hosting issue, so you might need to declare that variable as var index_array = ... Also, is the script tag where you set index_array being closed. It does not appear so from the screenshot. – Mike Brant Jul 31 '12 at 15:35
  • In the else also is alert, wich fires only when array is empty, but the var image_array works every time... I cant understand why? – user1564141 Jul 31 '12 at 15:38
  • @user1564141 It would help if you could update your question to show the source as output. I still don't have a feel for where your if-else logic resides within the source relative to the location of your index_array declaration. – Mike Brant Jul 31 '12 at 15:41
8

JavaScript

( typeof(myArray) !== 'undefined' && Array.isArray(myArray) && myArray.length > 0 )

Lodash & Underscore

( _.isArray(myArray) && myArray.length > 0 )
Amit Bhagat
  • 4,182
  • 3
  • 23
  • 24
6

You can use jQuery's isEmptyObject() to check whether the array 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 

Source: https://api.jquery.com/jQuery.isEmptyObject/

pushkin
  • 9,575
  • 15
  • 51
  • 95
Mayank Raipure
  • 1,773
  • 15
  • 12
  • This is the only thing that worked for me when adding elements with array.push() - from dynamically added elements (ajax). Thanks – TomoMiha Sep 09 '16 at 15:53
5

Using undescore or lodash:

_.isArray(image_array) && !_.isEmpty(image_array)

User5678015
  • 369
  • 4
  • 5
3

A simple way that doesn't result in exceptions if not exist and convert to boolean:

!!array

Example:

if (!!arr) {
  // array exists
}
insign
  • 5,353
  • 1
  • 38
  • 35
3

How about this ? checking for length of undefined array may throw exception.

if(image_array){
//array exists
    if(image_array.length){
    //array has length greater than zero
    }
}
  • The nested `if` can be avoided using `&&`, as in `image_array && image_array.length`, it will short circuit if `image_array` doesn't exist. – rvazquezglez Oct 26 '18 at 04:37
3

The best is to check like:

    let someArray: string[] = [];
    let hasAny1: boolean = !!someArray && !!someArray.length;
    let hasAny2: boolean = !!someArray && someArray.length > 0; //or like this
    console.log("And now on empty......", hasAny1, hasAny2);

See full samples list: code sample results

Oleksandr Yefymov
  • 6,081
  • 2
  • 22
  • 32
2

I come across this issue quite a lot in Javascript. For me the best way to do it is to put a very broad check before checking for length. I saw some other solutions in this Q&A, but I wanted to be able to check for either null or undefined or any other false value.

if(!array || array.length == 0){
    console.log("Array is either empty or does not exist")
}

This will first check for undefined, null, or other false values. If any of those are true, it will complete the boolean as this is an OR. Then the more risky check of array.length, which could error us if array is undefined, can be checked. This will never be reached if array is undefined or null, so the ordering of conditions is very important.

Jim Factor
  • 1,465
  • 1
  • 15
  • 24
1

If you do not have a variable declared as array you can create a check:

if(x && x.constructor==Array && x.length){
   console.log("is array and filed");
}else{
    var x= [];
    console.log('x = empty array');
}

This checks if variable x exists and if it is, checks if it is a filled array. else it creates an empty array (or you can do other stuff);

If you are certain there is an array variable created there is a simple check:

var x = [];

if(!x.length){
    console.log('empty');
} else {
    console.log('full');
}

You can check my fiddle here with shows most possible ways to check array.

Plippie
  • 2,836
  • 33
  • 28
1

The following is my solution wrapped in a function that also throws errors to manage a couple of problems with object scope and all types of possible data types passed to the function.

Here's my fiddle used to examine this problem (source)

var jill = [0];
var jack;
//"Uncaught ReferenceError: jack is not defined"

//if (typeof jack === 'undefined' || jack === null) {
//if (jack) {
//if (jack in window) {
//if (window.hasOwnP=roperty('jack')){
//if (jack in window){

function isemptyArray (arraynamed){
    //cam also check argument length
  if (arguments.length === 0) { 
    throw "No argument supplied";
  }

  //console.log(arguments.length, "number of arguments found");
  if (typeof arraynamed !== "undefined" && arraynamed !== null) {
      //console.log("found arraynamed has a value");
      if ((arraynamed instanceof Array) === true){
        //console.log("I'm an array");
        if (arraynamed.length === 0) {
            //console.log ("I'm empty");
            return true;
        } else {
          return false;
        }//end length check
      } else {
        //bad type
        throw "Argument is not an array";
      } //end type check
  } else {
    //bad argument
    throw "Argument is invalid, check initialization";;
  }//end argument check
}

try {
  console.log(isemptyArray(jill));
} catch (e) {
    console.log ("error caught:",e);
}
Tommie C.
  • 12,895
  • 5
  • 82
  • 100
1

the way I found to work (comming from another language) is to make a simple function to test.

create a function that check the size of the array and pass the lenght by parameter.

isEmpty(size){
        if(size==0) {
            return true;
        } else  {
            return false;
        }
    }

//then check
if(isEmpty(yourArray.length)==true){
            //its empty
        } else {
            //not empty
        }
Thiago Silva
  • 670
  • 6
  • 18
0

For me sure some of the high rated answers "work" when I put them into jsfiddle, but when I have a dynamically generated amount of array list a lot of this code in the answers just doesn't work for ME.

This is what IS working for me.

var from = [];

if(typeof from[0] !== undefined) {
  //...
}

Notice, NO quotes around undefined and I'm not bothering with the length.

Tom Stickel
  • 19,633
  • 6
  • 111
  • 113
  • 1
    two comments: 1) `typeof` returns a string, comparing to `undefined` will always be flasy 2) you don't check if `from` is defined. your code above will throw an error if it's not – Xeltor Oct 13 '17 at 14:54
0

You should do this

    if (!image_array) {
      // image_array defined but not assigned automatically coerces to false
    } else if (!(0 in image_array)) {
      // empty array
      // doSomething
    }
0

Probably your image_array is not array but some OBJECT with length property (like string) - try

if(image_array instanceof Array && image_array.length)

function test(image_array) {
  if(image_array instanceof Array && image_array.length) { 
    console.log(image_array,'- it is not empty array!')
  } else {
    console.log(image_array,'- it is empty array or not array at all!')
  }
}

test({length:5});
test('undefined');
test([]);
test(["abc"]);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

In my case, array_.length always returned 0, even if it had values inside. Probably, because of non-default indexes.

So to check if array is defined we use typeof _array !== 'undefined' And then to check if it contains any date i just simply compare it to an empty array _array !== []

Ivan Off
  • 25
  • 3
0

You can use:

if (Array.isArray(arr) && !arr.length) {
  console.log("Array is an array and is empty");
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Please re-read the question. It's interested in the condition where the array is non-empty, which is covered in [this answer](https://stackoverflow.com/a/20940191/) already. – General Grievance Mar 30 '23 at 12:39
  • 1
    Please elaborate on how your code works and how it fixes OP's problem – Rojo Mar 30 '23 at 13:05
-1

in ts

 isArray(obj: any) 
{
    return Array.isArray(obj)
  }

in html

(photos == undefined || !(isArray(photos) && photos.length > 0) )

velan
  • 37
  • 4
-4

When you create your image_array, it's empty, therefore your image_array.length is 0

As stated in the comment below, i edit my answer based on this question's answer) :

var image_array = []

inside the else brackets doesn't change anything to the image_array defined before in the code

Community
  • 1
  • 1
Al_th
  • 1,174
  • 1
  • 12
  • 24
  • I have it in the source, when loading page... Just forget to post. – user1564141 Jul 31 '12 at 15:21
  • I want to add something to my answer that may be wrong so i state it here. In common languages, what is created inside a block is not visible "outside" the block. As you define `[]var image_array = []` inside the else block, i'm not sure it could be seen outside. Try `image_array = []` – Al_th Jul 31 '12 at 15:26
  • but if i remove image_array from the else everything works just fine. – user1564141 Jul 31 '12 at 15:28