Is there any difference between checking an array's length as a truthy value vs checking that it's > 0?
In other words is there any reason to use one of these statements over the other:
var arr = [1,2,3];
if (arr.length) {
}
if (arr.length > 0) {
}
Is there any difference between checking an array's length as a truthy value vs checking that it's > 0? Since the value of arr. length can only be 0 or larger and since 0 is the only number that evaluates to false , there is no difference.
Arrays in Java use zero-based counting. This means that the first element in an array is at index zero. However, the Java array length does not start counting at zero.
A zero length array is simply an array with nothing in it. It is an advantage to have such an array, especially in Java, so you can return a valid array and guarantee that your length check never fails. In Java, an array even of primitive types (i.e. int[] ) is still an object. It has a length property.
No, the length of an array is a non-negative integer.
Is there any difference between checking an array's length as a truthy value vs checking that it's > 0?
Since the value of arr.length
can only be 0
or larger and since 0
is the only number that evaluates to false
, there is no difference.
In general, Boolean(n)
and Boolean(n > 0)
yield different results for n < 0
.
In other words is there any reason to use one of these statements over the other
Only reasons related to code readability and understanding, not behavior.
array.length
is fastest and shorter than array.length > 0
. You can see difference of their speeds : http://jsperf.com/test-of-array-length
if(array.length){...}
is similar to if(0){...}
or if(false){...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With