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
If there is no element in array, then
array.length === 0
condition works fine.An elegant way I feel is to use not operator
You can find more ways here enter link description here
For me comparing a number to 0 is useless since
0
is falsy (it actually detects a novice JS programmer for me), just use:Just check
a.length
itselfYour 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.