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

Can I use a function() for this exercise instead of while? Pls take a look at my code 🙏

//Instructor's code:

var message = '';
var student;

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

for (var i = 0; i < students.length; i += 1) {
  student = students[i];
  message += '<h2>Student: ' + student.name + '</h2>';
  message += '<p>Track: ' + student.track + '</p>';
  message += '<p>Points: ' + student.points + '</p>';
  message += '<p>Achievements: ' + student.achievements + '</p>';
}

//below is my code:

function simpleSearch () {
var search = prompt("Enter student name or type 'quit' to exit.");

 if (students.indexOf(search) > -1) {
   print(students[indexOf(search)]);
 } 
  else if (search === "quit") {
   return;   
 } 
  else {
   print("No records.");
}
}

  simpleSearch();

With my code, it can only quit or display "No records" and can't find the name of the student even if typed correctly. So the problem probably lies with this snippet:

if (students.indexOf(search) > -1) {
   print(students[indexOf(search)]);
 } 
Steven Parker
Steven Parker
243,266 Points

Where is the "while" you are referring to?

while (true) {....} as in the instructor, Dave's solution: https://teamtreehouse.com/library/the-student-record-search-challenge-solution (minute ~4:22) I should've included that 😅

1 Answer

Steven Parker
Steven Parker
243,266 Points

The content of "students" isn't shown here, but I expect that it is an array of complex objects. So when you call "students.indexOf(search)" you are attempting to find a match between a complex object and a simple string ("search"), which will always fail.

What you probably need here is a loop that will compare only the name attribute of each student object to the search string.

oh you're right. I got it now, thank you!!!! ❤