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?

Community
  • 1
  • 1
JVG
  • 20,198
  • 47
  • 132
  • 210
  • `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`?) – Felix Kling Dec 02 '13 at 09:22
  • Check [this question](http://stackoverflow.com/q/4725603/255756). There are some approaches for determining whether a variable is not defined. – Linus Kleen Dec 02 '13 at 09: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.** – Felix Kling Dec 02 '13 at 09:29

1 Answers1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875