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 trialNikola Jankovic
10,793 PointsI can not understand why this work this way. I runs if and else if every time. Can someone help?
var message= ''; var student; var question;
function print(message){ document.write(message); }
function getReport (student) { var report= '<h2> Student name is '+student.name+' </h2>'; report+= '<p> Student track is '+student.track+' </p>'; report+='<p> Student achivements are ' +student.achievements+ ' </p>'; report+= '<p> Student points are '+student.points+' </p>'; return report; }
while (true) { question= prompt('Who are you looking for?'); student=students[i] if (question=== null || question.toLowerCase()=== 'quit'){ break; }
for (var i=0; i<students.length; i+=1) {
student=students[i];
if (question.toLowerCase()=== student.name.toLowerCase()) {
print(getReport(student));
}else if (question !== student.name) {
alert('There is no one by that name!');
break;
}
}
}
2 Answers
Steven Parker
229,732 PointsThe loop performs the test for every student in the list.
So if you had a list of 4 students, and typed in a name that matched one of them, you would get 1 report and three alerts.
You probably want to restructure your loop so that the alert is only done after the loop completes, and then only if nothing was found and reported.
Nikola Jankovic
10,793 PointsThank you for your answer. I resolved this problems with this code:
var message= '';
var student;
var question;
var answer= false;
function print(message){
document.write(message);
}
function getReport (student) {
var report= '<h2> Student name is '+student.name+' </h2>';
report+= '<p> Student track is '+student.track+' </p>';
report+='<p> Student achivements are ' +student.achievements+ ' </p>';
report+= '<p> Student points are '+student.points+' </p>';
return report;
}
while (true) {
question= prompt('Who are you looking for?');
student=students[i]
if (question=== null || question.toLowerCase()=== 'quit'){
break;
}
for (var i=0; i<students.length; i+=1) {
student=students[i];
if (student.name.toLowerCase()=== question.toLowerCase() ) {
answer= true;
print(getReport(student));
}
}
if (! answer){
alert('This name is not in the records!');
}
}