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?

3
  • 2
    By "list", do you mean "array"? Commented Mar 10, 2020 at 8:13
  • 2
    Also, you can use just !list.length. For empty list, this will return true, else false. Commented Mar 10, 2020 at 8:18
  • 1
    No 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. Commented Mar 10, 2020 at 8:21

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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... :-)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.