Marco Jordan
Marco Jordan

Reputation: 147

Make a javascript function workable

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

Answers (4)

Thomas Junk
Thomas Junk

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

Denys S&#233;guret
Denys S&#233;guret

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

Andy
Andy

Reputation: 63550

if (place.reviews.length > 0)

Upvotes: 1

Tomzan
Tomzan

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

Related Questions