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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

Sarah Lehnert
Sarah Lehnert
9,405 Points

Why are we using a for loop with var i instead of .indexOf()

I am confused as to why we are using a for loop with var i for the search. Every time you run through the for loop "i" increases by 1. So theoretically, wouldn't you run out of searches after your 5th attempt (because student.length is 5)?

Additionally, doesn't it only search one student at a time. For ex. on the first search i = 0, so student = students[i] would send you to Dave's record. So when you search, even if you search Jody, it would be looking in Daves record and therefore return false

If not, why does this work?

CODE SNIPPET

while (true) {
 search = prompt("Search any student record. Example you can type 'Jody' or enter 'quit' to exit'");
 if (search.toLowerCase() === 'quit' || search === null ) {
   break;
 } else {
   for (var i = 0; i < students.length; i +=1) {
    student = students[i];
    if ( student.name === search) {
    message = getStudentReport( student) ; 
    print(message);
    } else {
    message = '<p> Sorry this student does not exist </p>';
    print(message);
    }
   }
 }
}

1 Answer

Steven Parker
Steven Parker
231,007 Points

The for loop stops after the last item.

You don't run out of items because the condition clause of the loop checks that the index is less than the length. When that's no longer true, the loop stops.

It does look like the code to print the "does not exist" message should be moved to after the loop. But at the moment, even though a spurious message will be printed, it doesn't interfere with the loop so the rest of the students will still be searched.