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

Daniel Stockham
Daniel Stockham
10,277 Points

Going through an infinite loop...

var message = '';
var student;
var search = prompt('Please enter name to search for recored or type "quit" to exit window');

function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}

function getStudentReport( student ) {
   var report = '<h2>Student: ' + student.name + '</h2>';
    report += '<p>Track: ' + student.track + '</p>';
    report += '<p>Points: ' + student.points + '</p>';
    report += '<p>Achievements: ' + student.achievements + '</p>';
   return report;
}
while (true) {

  if ( search === null || search.toLowerCase() == "quit") {
    break;
  }
 for (var i = 0; i < students.length; i += 1) {
   student = students[i];
   if (student.name === search) {
    message = getStudentReport( student );
    print(message);


   }



 }
}

I swear I put this in correctly but it keeps going through an infinite loop. What am I doing wrong?

2 Answers

It seems that you would want to repeat the search prompt at the bottom of the loop

    search = prompt('Please enter name to search for or type "quit" to exit window');
}

Code is more understandable if it doesn't break out in the middle. This would be a clearer option.

var search = prompt('Please enter name to search for or type "quit" to exit window');
while ( search !== null && search.toLowerCase() !== "quit") {
   .
   .
   .
   search = prompt('Please enter name to search for or type "quit" to exit window');
}
Francisco Monroy
Francisco Monroy
10,307 Points

I haven't tried it, but it looks like a flag can also help you exit the loop.

var flag = true;
while (flag) {
    if (search === null || search.toLowerCase() == "quit") {
        break;
    }
    for (var i = 0; i < students.length; i += 1) {
        student = students[i];
        if (student.name === search) {
            message = getStudentReport(student);
            print(message);
            flag = false;
        }
    }
}