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?
2 Answers
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 })
1 Comment
length, or creating an array-like with a negative length, there are other issues... :-)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
!list.length. For empty list, this will return true, else false.