Skip to content Skip to sidebar Skip to footer

Testing For An Empty Array

Are there any advantages to using one of following statements over the other to check for an empty array? if (arr.length) {} vs if (arr.length > 0) {} I'm assuming they are th

Solution 1:

if(typeof arr != "undefined" && arr != null && arr.length > 0){}

I was always told this was the correct way to check for empty arrays, and it's stuck with me.

So, to answer your question precisely:

if(arr.length > 0){}

Is the method I was led to believe was "correct", as it is clearer to anyone reading the code what the implied logic was. I believe this is likely why you see this method used in documentation/samples/tutorials over the other.

But as for any specific advantage other than semantic look and feel, I don't believe there is any.

A lot more explanation available on this question: Check if array is empty or exists

(linking, as I don't want to steal their descriptions - they deserve the upvotes)


Solution 2:

Since arr.length can't be negative, they will result in the same behaviour. In the first one, the integer value arr.length will be evaluated as true or false in a Boolean context (it's "truthy"): false if 0 and true otherwise. So it is the same as if(arr.length != 0). It all depends on what you think is the most legible.


Solution 3:

Generally, it should be the same because 0 is recognized as "false" (when converted into a boolean). But having a ">0" will make the code more readable, so I recommend using

if (arr.length > 0) {}

Speed-wise, they should be identical, or nearly so.


Solution 4:

One main difference would be for ease of code when testing multiple arrays for instance

if (arr.length && arr2.length && arr3.length) {}

This would be a lot easier than specifying > 0 constantly. Its another one of those things that is does the browser or javascript version support the shorthand. If your target audience was for people with an outdated browser you would probably want to use the full version.


Post a Comment for "Testing For An Empty Array"