I am used to check for empty arrays with array.length <= 0
. Of course the array should never have a length smaller than 0. This is a habit I developed to make sure my program runs "just in case something weird happens". Is there any reason not to use the <=
operator and use === 0
instead?
Asked
Active
Viewed 940 times
0

eddex
- 1,622
- 1
- 15
- 37
-
2By "list", do you mean "array"? – CertainPerformance Mar 10 '20 at 08:13
-
2Also, you can use just `!list.length`. For empty list, this will return true, else false. – palaѕн Mar 10 '20 at 08:18
-
1No need for strict comparison(===), in Javascript Array.length is type of positive number. So using == is fine. But if your array is undefined then you may end up in error, so it is better to check that also. Hope this helps. – R.Sarkar Mar 10 '20 at 08:21
2 Answers
4
If the list
is an array, then no, there's no chance of the length
being anything other than a whole number. From the specification:
Every Array object has a non-configurable "length" property whose value is always a nonnegative integer less than
2 ** 32
Given an array object, you couldn't even deliberately make things confusing by changing the length
to something other than a valid length; an error will be thrown:
const arr = [];
Object.defineProperty(arr, 'length', { value: -5 })

CertainPerformance
- 356,069
- 52
- 309
- 320
-
Of course, when you're dealing with proxies or array-likes... But if someone's creating an array proxy that returns a negative number for `length`, or creating an array-like with a negative length, there are other issues... :-) – T.J. Crowder Mar 10 '20 at 08:18
2
In my view, there is no reason to check negative value of length list.length <= 0.
as specs for Arrays says:
Every Array object has a length property whose value is always a nonnegative integer less than 232.
So it is perfectly eligible to check list.length === 0

StepUp
- 36,391
- 15
- 88
- 148