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.
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.
if (array.length) but I know other people who prefer `if (array.length > 0)if (arr.length > 0) is the more readable option. It tells anyone looking at your code that you expect arr to be a variable of a type that has a length property that is a number, and you are not expecting a case where arr.length = '', undefined, NaN, or null. It's more obvious to use this in the general sense, if (myVar.prop > 0), but I have seen code where the case where arr.length is undefined occurs.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){...}
array.length ran slower for me than array.length > 0 in Chrome 59. Not sure how that's possible since intuitively it seems like it would be doing less.Boolean(array.length) when the > 0 is not present. There are a lots of different values that can be true or false in javascript and they all require a check (null, false, undefined, 0, '', etc.)In javascript, they dont make a difference.
In the end, whatever is in between the if parenthesis will evaluate to a truthy or falsey value
For all possible falsey values, see All falsey values in JavaScript
If you wish to be more clear and explicit, use
if (arr.length > 0) {
}
If you wish to be less verbose, use
if (arr.length) {
}
if(arr[0])works just fine too.