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 { ...
To check if an array is empty in React, access its length property, e.g. arr. length . If an array's length is equal to 0 , then it is empty. If the array's length is greater than 0 , it isn't empty.
To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With