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

objects students challenge part 3

Hello, I was trying to build on some of the challenge and I wanted to it to send an alert if the student you search for is not in the objects array. I am able to get the alert but it seems to be stuck in the loop so the alert comes on 4 times before I can input anything else. I was wondering if anyone could help me figure this out. Thank you in advance. Excuse all my comments in the code.

var message = '';
var student;
var search;
var foundStudents = [];



function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}
/* to build this function first we make the funtion and add the paramenter we need in this case I used the word report
then I set the var also called report(its a local variable) to equal the first part of our final output message
then I built the message up with the += for every value in the student key
then I return the report and the function is ready
*/
function buildReport( report) {
  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;
}

// first I make an infinite loop
while (true) {
  //then I use the search variable declaired up top to prompt the user for input
  search = prompt("Please search students by name or type 'quit' to exit");
  //if the user input is equal to 'quit' in any case they type it or to null(nothing) then
 if ( search.toLowerCase() === 'quit' || search === null) {
   // this alert will show
    alert("Thank you.  Have a great day")
  // the look will break (ie stop) and the program will end 
    break;
  // however, if they type in a name we got into this loop. This loop goes through the array of objects
 } for (var i = 0; i < students.length; i += 1) {
  // it gets the students information. Each item in 0 index in the array so first loop is 0 array index
    student = students[i];
  //Once I have student set to I it will loop and search for the name that is input. If the name matches
  if (student.name.toLowerCase() === search.toLowerCase()) {
    //we set the variable message to equal the function we made and pass it the student as paramenter
    foundStudents.push(student);
    message += buildReport(foundStudents);
    //now the message var holds the student information so we print it out
    print(message);
} else {
        alert("Sorry No student found");
  }
 }
}

4 Answers

Steven Parker
Steven Parker
243,215 Points

FIrst off, don't apologize for comments — comments are good! :wink: And if you put "js" after the three accents that mark the start of the code block, you'll get syntax coloring that will make them easy to spot.

Then, remember that your loop is checking for a match with each student, one at a time. So if you "alert" each time the match fails, you'll get one for each student in the array.

For what you want to do, the alert should only be done after the loop is finished. If you keep track of whether any match was found (perhaps with a boolean variable), you can check it after the loop is done to see if you should perform the alert.

Bonus tip: It looks like you continually concatenate found students onto "message". You may want to either clear it at some point, or just do simple assignment instead of concatenation.

Steven Parker Thank you for your reply and for teaching me how to properly display my code. I understand that my the alert is popping up each time the match fails but I don't understand where I should be putting the alert so that it only runs after the loop is done. I played around with your suggestion about using a boolean value. I came up with this and it seems to be better but now the alert never shows up. If you don't mind could you tell me if I am on the right track? also, thank you for the bonus hint! I will get on that as soon as I get this sorted. It's really bothering me that I can't figure it out. I feel like it isn't anything difficult.

var message = '';
var student;
var search;
var foundStudents = [];
var matches;



function print(message) {
  var outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}
/* to build this function first we make the funtion and add the paramenter we need in this case I used the word report
then I set the var also called report(its a local variable) to equal the first part of our final output message
then I built the message up with the += for every value in the student key
then I return the report and the function is ready
*/
function buildReport( report) {
  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) {
  search = prompt("Please search students by name or type 'quit' to exit");
  if ( search.toLowerCase() === 'quit' || search === null) {
    alert("Thank you.  Have a great day")
    break;
      } for (var i = 0; i < students.length; i += 1) {
        student = students[i];
        matches = true;
        if (student.name.toLowerCase() === search.toLowerCase()) {
          foundStudents.push(student);
          message += buildReport(foundStudents);
          print(message);
        } else if (matches !== true) {
          alert("Sorry, No student found");
        }
     }
   }
Steven Parker
Steven Parker
243,215 Points

Perhaps this code excerpt will clarify what I was suggesting:

  matches = false;     // reset boolean BEFORE the loop
  for (var i = 0; i < students.length; i += 1) {
    student = students[i];
    if (student.name.toLowerCase() === search.toLowerCase()) {
      matches = true;  // set boolean only when match is found
      // (printing stuff)
    }
  }                    // <- loop ends here
  if (!matches) {      // NOW check the result and show message
    alert("Sorry, No student found");
  }

I was looking at the bonus tip. At the end of my program, the array with the found students list is displayed like this: Student: Jon Track: iOs

Points: 1925

Achievements: 10

Student: Omar Track: Full Stack Javascript

Points: 1225

Achievements: 12

So I thought that clears the array for the next time its input. I am quite new at this so sorry if I am asking too many questions but I was wondering if there is a reason why I would want to clear the array? Once the program ends all the items in that array are gone, or so I think they are.

Steven Parker
Steven Parker
243,215 Points

But if you look up one student, and then look up another, won't the display show the first one twice?

Steven Parker, I understand now. I was thinking about it all wrong! I was thinking I should set a boolean variable and to true then put it in like this

while (true) {
    search = prompt("Please search students by name or type 'quit' to exit");
    if ( search.toLowerCase() === 'quit' || search === null) {
      alert("Thank you. Have a great day")
      break;
        } 

        for (var i = 0; i < students.length; i += 1) {
          student = students[i]; 
          if (student.name.toLowerCase() === search.toLowerCase()) {
            matches = true;
            foundStudents.push(student);
            message += buildReport(foundStudents);
            print(message);
          } 
         } if (!matches) {
          alert("no student found");
        }
     }  

I didn't think that I need to reset the true and false. Its like an on/off switch! I understand now. Thank you very much for your time. I will not look at fixing the extra hint part. Thank you again!

Steven Parker Do you mean if I look up, for example, Jon then Omar it will display Jon twice then Omar? It doesn't do that but I just noticed that if I search for Jon then Omar then Jon again it will display both Jon searches, which are the same person. I didn't know that until now hahaha. Also, I really wanted to thank for all your help so far I've learned a lot from this.

Steven Parker
Steven Parker
243,215 Points

I didn't have your data file so I did not try it, but just looking at this line:

            message += buildReport(foundStudents);

I got the impression that since it was concatenating onto "message", that unless it was reset at some point, every time you printed a new output it would also repeat everything it had printed before.

If it doesn't do that, perhaps I missed something and you can disregard that suggestion.

Steven Parker, It's not doing that it just prints every name once. Thank you again. You should teach a course!