Search code examples
javascriptdefensive-programming

When checking if an array is empty, should I use array.length <= 0 or array.length === 0?


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?


Solution

  • 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 })