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

Nathan Marshall
Nathan Marshall
6,031 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

Thanks,

Nathan

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');
outputDiv.innerHTML+=message

}

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');
        break;
      }

}

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.