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

Why does the loop stop working?

Hey everyone! I have a list of students (in an object) and I need to find whose name is equal to the name the user typed. My code is working (so-so) but when there's more than one match it only displays the first one. Why does it stop after the first match (the object is in another file)?

  • Sorry I'm really bad at posting code to TreeHouse, it looks better on my platform. ^^

var student; var plug = false;

while(true) {

   var search = prompt('Type a name to find a student or "quit" to close the window!');
   if(search.toLowerCase() === 'quit' || search === null) {
      break;
   }else {
         plug = false;
         for (var i = 0; i < students.length; i += 1) {
            student = students[i];
            if(student.name.toLowerCase() === search.toLowerCase()) {
               plug = true;
               var message = '';
               message += '<h2>' + student.name + '</h2>';
               message += '<ul><li>' + '<strong>track:</strong> ' + student.track + '</li>';
               message += '<li>' + '<strong>achivements:</strong> ' + student.achievements + '</li>';
               message += '<li>' + '<strong>points:</strong> ' + student.points + '</li></ul>';
               print(message);
           }
        }
    if(plug === false) {
        alert('The student was not found!');
    } 
 }

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

}

3 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I believe that the placement of this line is your problem:

var message = '';

This line occurs every time a match is found, which means that every time a match is found the message is being cleared out completely. Try using this line towards the top of your file and see if that helps.

Let me know how it goes! :sparkles:

Hi David, post the 'student' object to help analyze your code better.

You were right, thank you!! :) I really need to get used to this "output" method... :)