0

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 ... ?

2
  • You can try place.reviews[0] as condition to if statement. Commented Sep 16, 2013 at 11:18
  • Can place.reviews be undefined ? Commented Sep 16, 2013 at 11:22

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This will continue if the array is empty tho.
2

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.

1 Comment

+1 because if the array is guaranteed being defined and being an array, then it's the best solution.
1

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>';
    }   

Comments

1
if (place.reviews.length > 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.