1

I have a javascript query like this that is meant to check both undefined arrays and empty arrays:

if(array){
    if(array.length > 0){
       function1();
    }else{
       function2();
    }
}else{
    function2();
}

I've tried something like

if(array && ( array.length > 0)){
    function1();
}else{
    function2();
}

but no dice, get a variable is undefined error. According to this answer doing if(variable) works just fine for this use-case, but this only works on strings rather than arrays. Is there any way to do two-in-one in javascript in a case like this?

3
  • if(array && ( array.length > 0)){ should work fine. If you get an error, it's unrelated or array is not declared (maybe you get a ReferenceError?) Commented Dec 2, 2013 at 9:22
  • Check this question. There are some approaches for determining whether a variable is not defined. Commented Dec 2, 2013 at 9:24
  • If you get a reference error, then I wonder where array is supposed to come from? As long as you are not integrating two independent scripts somehow, any variable should be at least declared. Please provide more context. Commented Dec 2, 2013 at 9:29

1 Answer 1

6

...I get a variable is undefined error

That means array isn't declared at all anywhere. To defend against that, you can use typeof:

if (typeof array !== "undefined" && array && array.length > 0)

Live Example | Source

There's a difference between a symbol being completely undefined, and a defined symbol resolving to a variable that contains the value undefined. Confusing, but true. You can safely use typeof on anything, even something that is completely undeclared anywhere, but if you try to read the value of something that isn't declared anywhere, you'll get that ReferenceError saying it doesn't exist.

Sign up to request clarification or add additional context in comments.

3 Comments

If you do typeof array !== "undefined", I'd argue that the second test, array, is unnecessary.
@FelixKling: Yeah, although it could have the value null. Trying to read length from null would give us an error.
Forgot about null :-/ I should go to sleep.

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.