Since people are often using
array.length < 1
to check if an array is empty instead of
array.length === 0
I wonder if there are cases array.length could be below 0.
Since people are often using
array.length < 1
to check if an array is empty instead of
array.length === 0
I wonder if there are cases array.length could be below 0.
Share Improve this question asked Nov 19, 2011 at 0:08 ajsieajsie 79.7k110 gold badges284 silver badges386 bronze badges 2- 2 Your question is incomplete. Don't forget about rulling out fractional lengths, like 0.5 ;) – hugomg Commented Nov 19, 2011 at 0:14
- @missingno: I went ahead and answered that part, too. ;-) – T.J. Crowder Commented Nov 19, 2011 at 0:22
1 Answer
Reset to default 23No, the length
of an array is a non-negative integer. From the spec:
Every Array has a non-configurable "length" property whose value is always a non-negative integral Number whose mathematical value is less than 2^32.
(my emphasis)
So either check is perfectly fine, and both will have the same result for all arrays.
You may find people arguing for === 0
over < 1
on the grounds of performance, because the IsStrictlyEqual algorithm would take fewer steps than the IsLessThan algorithm. Granted that's true, but I'm aware of no evidence that either is faster than the other in this use-case (and I've tested it; sadly the jsPerf test is gone now). (Or others may argue that <
will do type conversion and ===
won't, but that's irrelevant here; both types are the same.) But even if it were that one was minutely faster than the other, you'd have to be doing the comparison literally billions of times to see even the smallest real-world impact.