Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could array.length be below 0 in Javascript?

Tags:

javascript

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.

like image 950
ajsie Avatar asked Nov 19 '11 00:11

ajsie


1 Answers

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.

like image 102
T.J. Crowder Avatar answered Oct 27 '22 13:10

T.J. Crowder