How can I check if an array is empty with a IF statment?
I have this array 'acessos' that's empty
...
constructor(props){
super(props);
this.state = {
acessos:[]
};
}
...
Then I'm trying to check if 'acessos' is empty and if it is I push some data in it. I've tried with null but with no results, so how can I check if is empty?
...
if(this.state.acessos === null){
this.state.acessos.push({'uuid': beacons.uuid, 'date':date});
this.setState({acessos: this.state.acessos});
} else {
...
6 Answers 6
I agree to Julien. Also you don't have to compare it to null. You can write it like
this.state.acessos && this.state.acessos.length > 0
Comments
Just check if your array exists and has a length:
if (this.state.products && this.state.products.length) {
//your code here
}
No need to check this.state.products.length > 0
. 0
is falsy anyway, a small performance improvement.
Comments
If checking the array length as part of conditional rendering in React JSX, remember that if condition is falsy at length check, it will render a 0 as in the following example:
{myArray && myArray.length && (
<div className="myclass">
Hello
</div>
)}
This is not what we want most of the time. Instead you can modify the JSX as follows:
{myArray && myArray.length? (
<div className="myclass">
Hello
</div>
):""}
Comments
You need not even check for the length since ECMAScript 5.1 You can simply write the same condition as follows.
this.state.acessos && this.state.acessos.length
By default this.state.acessos.length
checks if the length is NOT undefined or null or zero.
Comments
instead ofnull
its better to replace ""
like this if ( this.state.acessos == ""){}
2 Comments
acessos
is not a string, so why would you compare it to a string? You must provide an informed solution, and not simply an opinion such as "I think that..., it's better to...". I suggest you edit this answer to explain the why, or remove it. Array?console.log('array is empty'):console.log('array have values')
or
if (Array){
console.log('array is empty')
else{
console.log('array have values')
}
if(!this.state.acessos.length) { ... }
setState
instead. The documentation states "Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable." Meaning you should avoid doing things likethis.state.acessos.push(...);
Technically what you're doing there works fine because you are usingsetState
after, but I wanted to point that out for anyone else happening across this.this.setState({ acessos: [...this.state.acessos, { uuid: ... }] })
would accomplish this. But as I mentioned, what you have works because you are callingthis.setState
after mutating it. I just wanted to make sure it was clear that mutating items in the state directly and not callingthis.setState
after would be problematic.