Reputation: 147
Here I have an array place.reviews
but this array is sometimes empty so I need to write a function that first will check array is empty ot not and if not then to go getting data from array...
SO I try:
if (!!place.reviews) for(var i=0;i<place.reviews.length;i++){
contentStr += '<br>'+ place.reviews[i].text+ '</br>';
}
But this code dont work for me?
Is here problem with if (!!place.reviews)
or ... ?
Upvotes: 0
Views: 86
Reputation: 5676
Why check for emptyness at all?
for(var i=0;i<place.reviews.length;i++)
Your for loop-body doesn't execute at all if place.reviews.length is 0.
Upvotes: 2
Reputation: 382274
That's because any not null object is "truthy".
Assuming your array might be undefined
(if it can't there's no point in testing before the loop), you should do
if (place.reviews && place.reviews.length)
Upvotes: 2
Reputation: 2818
Your if statement is not well formed, use this:
if (place.reviews.length)
for(var i=0;i<place.reviews.length;i++) {
contentStr += '<br>'+ place.reviews[i].text+ '</br>';
}
Upvotes: 1