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.
No, 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.
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