15

I'm getting back the following JSON:

{"array":[],"object":null,"bool":false}

And I'm testing it with the following, seemingly exhaustive, if statement:

$.ajax({
        type: "GET",
        url: "/ajax/rest/siteService/list",
        dataType: "json",
        success: function (response) {
            var siteArray = response.array;

            // Handle the case where the user may not belong to any groups
            if (siteArray === null || siteArray=== undefined || siteArray=== '' || siteArray.length === 0) {
                            window.alert('hi');
            }
       }
});

But the alert is not firing. :[

5
  • 3
    What does console.log(siteArray) show you? Commented May 3, 2013 at 2:23
  • []. I tried if siteArray === "[]" but that didn't work either Commented May 3, 2013 at 2:25
  • An empty array is not the same as null, undefined, et al. Commented May 3, 2013 at 2:25
  • .length === 0 doesn't catch it either tho Commented May 3, 2013 at 2:27
  • What does console.log(siteArray.length) show you? Commented May 3, 2013 at 2:28

2 Answers 2

28

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

That did it, and it's much more elegant
That's an unfortunate resolution to the question. Why does this work but OP's code didn't?
7

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)

2 Comments

@Dennis Good point, it was scrolled off the window and I didn't see it. Nonetheless, it will work for an empty array. More data is needed :/
I was wondering why my comparison wasn't working. That makes a lot of sense thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.