skip to Main Content

I am working on a React project which involves making queries to a Firebase database to check if a username has been taken. The result I get from the query would be an array. When the array is not empty, it means there is a matching result, and therefore the username is not available.

I could see in the database there is a matching result and I tried to register using the same username to test, so there should be one item in the returned array.

First I set my condition as

if(array.length > 0) {

alert("Username is not available")

}

And it didn’t work, until I changed it to (with all other code unchanged)

if(!(array.length === 0)) {

alert("Username is not available")

}

Then it stared working.

I was just curious as to how the first one didn’t work as I expected. I don’t believe an array length could be less than 0. So this case, wouldn’t these 2 conditions basically do the same thing? Is there anything I am missing here?

5

Answers


  1. If there is no element in array, then array.length === 0 condition works fine.

    Login or Signup to reply.
  2. An elegant way I feel is to use not operator

    if (!array.length) do something;
    

    You can find more ways here enter link description here

    Login or Signup to reply.
  3. For me comparing a number to 0 is useless since 0 is falsy (it actually detects a novice JS programmer for me), just use:

    if(array.length) {
      alert("Username is not available")
    }
    
    Login or Signup to reply.
  4. Just check a.length itself

    > a=[]
    []
    > if(a.length) { console.log("true") }
    
    > a=[1]
    [ 1 ]
    > if(a.length) { console.log("true") }
    true
    
    > a=["1","2"]
    [ '1', '2' ]
    > if(a.length) { console.log("true") }
    true
    
    Login or Signup to reply.
  5. Your first method (array.length > 0) works, and I think it’s more readable than relying on implicit casting.

    Review the response of the call to make sure it’s returning an array or a map.

    If it doesn’t and returns a non-iterable object, !(array.length === 0) will result in true because array.length would be undefined, and indeed it’s not 0.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search