John John - 3 months ago 9
Javascript Question

Execute the else statement if none of the items are found

I have this for loop, and I would like to execute the else in the for loop only if none of the if conditions are met. The for loop runs until every item in the database has been checked. If none of the items in the database matches the user input then I want to run the else.

Right now, it runs the else right after the first try which means if the item matches is in the last row, it will just throw it in the error page since it stops the evaluation at the first iteration.

for(var i=0; i< rows.length; i++) {

if (rows[i].hashtag == userEnteredHashtag) {
// Display the choose Box page
res.render('chooseBox', {});
}


else {
// Display the invalid hashtag page
res.render('invalidHashtag', {});
}
}

Answer

Just move the else portion outside of the loop and execute it based on a flag

var wasFound = false;
for (var i = 0; i < rows.length; i++) {

   if (rows[i].hashtag == userEnteredHashtag) {
     // ...
     wasFound = true; // set the flag here
   }
 }

if (!wasFound) {
  res.render('invalidHashtag', {});
}