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

I finally got my 'student search' code to work, but one thing I don't understand

In my code below, I had originally tried to use the "alert()" function to state that the 'student' had not been found. This had caused it not to work and report that the 'student' had not been found, even when it I knew it existed in the array. My best guess is that it was looping through the entire code for every object literal in the array (as it threw up the not found message 5 times). After hours of tinkering and looking at other people's code, I finally realised that I should have been using the print function rather than alert(). This alone seems to have fixed it but I don't really get why it would have changed the looping thing; indeed if I change it back to alert() it starts misbehaving again. Anyway it would be good to know why this is for my own learning.

var message = '';
var student;

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

while (true) { search = prompt("Search records: type a name [jody] [or type 'quit' to end]");
                 if ( search === null || search.toLocaleLowerCase() === 'quit' ) { 
  break; }
              else {
           for ( var i = 0; i < students.length; i += 1) {
      var student = students[i].name.toLowerCase();
      search = search.toLowerCase(); 
                if (search === student) {
  message += '<h2>Student: ' + students[i].name + '</h2>';
  message += '<p>Track: ' + students[i].track + '</p>';
  message += '<p>Points: ' + students[i].points + '</p>';
  message += '<p>Achievements: ' + students[i].achievements + '</p>';
                print(message); 
                break; }

    else { print(search + " not found, sorry") } 
           } }
             }

1 Answer

Steven Parker
Steven Parker
231,153 Points

The "print" function replaces a string on the page, so you won't notice a difference if it does it once or multiple times.

But a better way to do this is to set a boolean inside the loop, and only issue a message (by any method) after the loop finishes based on the final value of that boolean.