1

I have a loop with inner if statements as follows

var html = "";
var i;
for (i = 0; i < products.length; i++) 
{
  if(products[i].attrs.product_type == type) 
  {
   html += '<p>hello world</p>';      
  }
}

I'd really like to be able to say if no results are returned from for loop, say "Sorry, no results were found" etc… I've tried the following… 

for (i = 0; i < products.length; i++) 
{
  if(products[i].attrs.product_type == type) 
  {
   html += '<p>hello world</p>' +i;      
  }
}

But that just puts the object number next to the returned result…

Any help would be great as I'm sure this is very easy

Thanks

  • at a high level, what you should do is set some variable outside the loop equal to false/zero, then within the loop set it to true/1 and do a check on that variable after the loop is done. If it's still equal to false/zero, you'll know that nothing met the loop conditions. – user2366842 Jul 03 '17 at 16:15
  • So if the length is zero than output that message..... What does `i` have to do with no results? – epascarello Jul 03 '17 at 16:16

3 Answers3

2

At the end check whether the html variable is actually filled, if not we didn't find any items and we can use the sorry message:

var html = '';
var i;
for (i = 0; i < products.length; i++) 
{
  if(products[i].attrs.product_type === type) 
  {
   html += '<p>hello world</p>';      
  }
}    

if (html === '') { // or: "if (!html)" if you like that sort of thing
  html = 'Sorry, no results were found'
}

Also notice that I changed the comparison from == to ===. That's because == tries to convert the type. While === does not. Use === to prevent strange errors, usually that's the one you want. For more info on it: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Updated because of comment by @ASDFGerte

shotor
  • 763
  • 6
  • 17
  • Your code appears to be checking whether `products` has zero length, not whether the loop has any results. – ASDFGerte Jul 03 '17 at 16:23
0

Similar to shotor's answer, but a slightly different approach would be as follows:

 var html = "";
 var i;
 var found = false;
 for (i = 0; i < products.length; i++) 
{
     if(products[i].attrs.product_type === type) 
   {
     html += '<p>hello world</p>' +i;
     found = true;      
   }
}    

if (found === false)
  {
    //do stuff here.
  }
user2366842
  • 1,231
  • 14
  • 23
0
var html = "";
var i;
var hasResult = false;
for ( i = 0; i < products.length; i++ ) 
{
  if( products[i].attrs.product_type == type ) 
  {
        html += '<p>hello world</p>';
        hasResult = true;
  }
}

if( !hasResult ){

    html = "No match";
}
sudip
  • 2,781
  • 1
  • 29
  • 41