Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

Konstantin Shabanov
Konstantin Shabanov
3,505 Points

Need help with code!

Hey guys,

Idk what is wrong but for some reason code doesn't print out information. 'Quit' works perfectly however, if I type name it just asks again.

Would appreciate any help.

https://w.trhou.se/vq2p3xxei6

1 Answer

Emmanuel C
Emmanuel C
10,636 Points

Hi,

Your while loop is set to true and only breaks if search is null or 'quit'. Which means even if you enter a correct name the loop doesnt break and you come back to the beginning of loop without reaching your for loop. You need a way to escape that loop if your user enters a correct name. You can put your for loop inside your while loop and use a flag to either exit or repeat the loop.

var flag = true;

while(flag) {
  search = prompt('Search student records: type a name [Kebab] (or type "quit")');
  if (search === null || search.toLocaleLowerCase() === "quit") {
    flag = false;
  }

  for (var i = 0; i < students.length; i+=1) {
    student = students[i];
    if (student.name === search) {
          message = getStudentReport (student);
          print(message);
      flag = false;
    }
  }


}

Theres a flag variable that starts as true to get the loop going, Then you ask for the name, immediately after, you check if the name is in your list and if it is, it processes your report and prints it but notice that it also sets the flag to false which allows you to exit the loop. If the name is not in the list the flag will stay true which mean the loop will start over asking the user again for another name. And if you enter quit or null the flag will become false and the loop ends.

Hopes this helps!