Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array.length vs. array.length > 0

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) {
}
like image 347
Ben Avatar asked Oct 02 '15 16:10

Ben


People also ask

Is array length is same as array 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.

Does length of array include 0?

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.

What is an array of length 0?

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.

Can an array length be less than 0?

No, the length of an array is a non-negative integer.


2 Answers

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.

like image 164
Felix Kling Avatar answered Sep 29 '22 05:09

Felix Kling


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){...}

like image 38
Sherali Turdiyev Avatar answered Sep 29 '22 06:09

Sherali Turdiyev