Array.length vs. array.length> 0

Is there any difference between checking the length of the array as a plausible value and checking that it is> 0?

In other words, is there any reason to use one of these statements over another:

var arr = [1,2,3]; if (arr.length) { } if (arr.length > 0) { } 
+7
javascript arrays
source share
3 answers

array.length is the fastest and shortest than array.length > 0 . You can see the difference in their speeds: http://jsperf.com/test-of-array-length

if(array.length){...} is similar to if(0){...} or if(false){...}

+2
source share

Is there any difference between checking the length of the array as a plausible value and checking that it is> 0?

Since the value of arr.length can only be 0 or more, and since 0 is the only number that evaluates to false , there is no difference.

In the general case, Boolean(n) and Boolean(n > 0) give different results for n < 0 .

In other words, is there any reason to use one of these statements over another

Only reasons related to code readability and understanding, not behavior.

+9
source share

In javascript, they have no meaning.

In the end, anything between the if bracket will be evaluated as true or false.

For all possible false values, see All false values ​​in JavaScript

If you want to be more clear and explicit, use

 if (arr.length > 0) { } 

If you want to be less detailed, use

 if (arr.length) { } 
+5
source share

All Articles