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 trialMatt Topping
4,527 PointsFinding if student exist
Hey all, having trouble getting a proper return for students not found. Because of the for loop it will run the not found code prior to returning student data. is there a way that indexOf() could fix this?
thank you
var html = '<ul style="list-style-type:none">';
var student;
var search;
var message = '';
var innerDiv = document.getElementById("output");
function isaStudent (search){
for (var i = 0; i < students.length; i++) {
if (search === students[i].name) {
return true;
} else {
return false;
}
}
}
function print(message) {
var text = document.getElementById("output");
text.innerHTML += message;
}
function getStudentReport(student){
var html = '<h2>Student: ' + student.name +'</h2>';
html += '<p>Track: ' + student.track +'</p>';
html += '<p>Achievements: ' + student.achievements +'</p>';
html += '<p>Points: ' + student.points +'</p>';
return html;
}
while (true) {
search = prompt('Find a student by first name [Kai,Nathan, etc.] "Quit" to exit');
innerDiv.innerHTML = '';
if (search === null || search.toUpperCase() === 'QUIT'){
print('<h1>Goodbye</h1>');
break;
} else if (isaStudent(search) != true){
alert('Sorry, ' + search + ' is not enrolled here.');
}
for (var i = 0; i < students.length; i++) {
student = students[i];
if (student.name === search) {
message = getStudentReport(student);
print(message);
}
}
}
//console.log(isaStudent(students[0].name));```
1 Answer
Steven Parker
231,533 PointsYou don't want your search to give up on the first test.
Wait until the loop has finished checking all students before returning false:
function isaStudent (search){
for (var i = 0; i < students.length; i++) {
if (search === students[i].name) {
return true;
}
}
return false;
}
Matt Topping
4,527 PointsMatt Topping
4,527 PointsWoah, smooth as butter now. So then, if on the first loop it does not find the search value it automatically defaults to the else statement? Then that is why it was returning false, if I'm understanding correctly... :?
-Thanks Steven!