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.

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge

Nathan Marshall
Nathan Marshall
6,019 Points

How does JavaScript know to match a searched name to [i] / a number

Hi Guys,

I have managed to complete the challenge, it seems to be working on my end but I don't understand why it works? I don't understand how javascript knows how to match the searched name to a number ( students[i] )?

If someone could take a moment to explain this to me, please?

My code is below



var students = [

{ name:'Corey', track:'Web Design' , achievements: 234, points: 7000,

}, { name:'Micheal', track:'Front End Development', achievements: 344, points: 7870,

}, { name:'Jason', track:'Back End Development' , achievements: 435, points: 10234,

}, { name:'Daniel', track:'Ios Development' , achievements: 3435, points: 234254,

}, { name:'Johnny', track:'Full Stack JavaScript' , achievements: 3736, points: 343542,



function print(message){

var outputDiv = document.getElementById('output');


while (true){

  var search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');  

    for (var i = 0; i< students.length; i++){

      if (search === students[i].name ){

        alert('match found')

         print('<li>' + '<strong>' + 'Student: '+ students[i].name + '</strong>' + '</li>');
         print('<li>' + 'Track: '+ students[i].track + '</li>');
         print('<li>' + 'Achivements: '+ students[i].achievements + '</li>');
         print('<li>' + 'Points: '+ students[i].points + '</li>' + '<br>'+'<br>');



      if ( search.toLowerCase() === 'quit') {
        alert('You have successfully quit');


1 Answer

With your for loop you are adding 1 to i each time the loop happens, which is after any time the prompt is answered. if (search === students[i].name ) is inside of that for loop, which means if the first item which will be students[0].name due to i starting equal to 0, the first item in the array, then the code inside your if block will trigger. So, if you searched Daniel, the if statement while debugging would be something like if ( search === students[3].name) Which would match up with Daniel as you're specifically targeting the name field on the objects in the array.