Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Christopher Judas
5,499 PointsHow can I stop this from printing 'Student Not Found' for each iteration of [i] where student.name != search?
I think I understand why the if...else statements in the for loop are causing the problem, but nothing I've tried seems to fix it. Does anyone have any suggestions?
I really just want it to print "Student Not Found" once if the name isn't in the students.js file.
var message = '';
var student;
var search;
function print(message) {
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) {
search = prompt("Search student records: type a name [Jody], or type 'quit' to end.");
document.getElementById('output').innerHTML = "";
if (search === null || search.toLowerCase() === 'quit') { break;}
for (var i=0; i<students.length; i++) {
student = students[i];
if (student.name.toLowerCase() === search.toLowerCase()) {
message = getStudentReport(student);
print(message);
} else {
print('Student Not Found');
}
}
}

Christopher Judas
5,499 PointsThanks Steven Parker, I made that change - it should work correctly now.
1 Answer

Steven Parker
216,149 Points
You need to print your message after the loop, not inside it.
You can set a boolean in the loop if you find anything, and test it to see if the message should be used at all:
var notfound = true; // assume none will be found
for (var i=0; i<students.length; i++) {
student = students[i];
if (student.name.toLowerCase() === search.toLowerCase()) {
message = getStudentReport(student);
print(message);
notfound = false; // remember we found at least one
}
}
if (notfound) {
print('Student Not Found');
}

Christopher Judas
5,499 PointsAha! Thanks again!
Steven Parker
216,149 PointsSteven Parker
216,149 PointsThe "link to source" was a good idea, but...