jossr jossr - 7 months ago 27
Javascript Question

if-else statement nested in while-loops

I am a beginner when it comes to Javascript. I am not really sure where to ask appropriately and I thought since I've been stalking Stack Overflow for awhile now, this might be the right time to finally make an account and start my profile here. The book I am reading doesn't really have a Help Forum of any sort.

Anyways, I am reading a book that is in tandem with some JS exercise and I wanted to try combining principles of while-loops that contain nested if..else statements. My code is below :

var teams = ["Chiefs", "Bees", "Tigers", "Bears"];
var i = 0;
while (i < teams.length) {
if (teams[i] === "Lions") {
alert(teams[i] + " is at Index " + i + " in the array");
break;
} else {
alert("Query not found!");
break;
}
i++;
}


The exercise was only suppose to be using the concept of while and if but obviously with my curiosity into programming I wanted to add the else statement but I cannot get the code to work. The only instance I got the code to work properly was without the else statement.

My main goal/curiosity is I would like it to alert "Query not found!" when the if statement can't find the string in the array, in this case I've written "Lions".

Thank you for your help in advance!

Answer

You can decide whether something is found when you find it. But you can only decide something is not found when you've looked at everything, which should be outside the loop.

var teams = ["Chiefs", "Bees", "Tigers", "Bears"];
var i = 0, position = null;
while (i < teams.length) {
  if (teams[i] === "Lions") {
    position = i;
    break;
  }
  i++;
}
if (position !== null) {
  alert(teams[position] + " is at Index " + position + " in the array");
} else {
  alert("Query not found!");
}