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

"if (student.name === search)" — why does this work?

In the video, this snippet of code is used to check if the user's search term matches a name in the student record:

for ( var i = 0; i < students.length; i += 1 ) {
  student = students[i];
  if ( student.name === search ) {
    message = getStudentReport( student );
    print(message);
  }
}

I don't get why would "if (student.name === search)" work.

Let's say that we're making the first loop, where "i = 0". That would make "student.name" in effect be "students[0].name", which maps it to a specific student each round (in this case, it's "Dave".)

So if during the first search, where "i = 0", I look up "Jody", using the "if (student.name === search)" code, wouldn't it return with "(Dave !=== Jody)"?

Which is to say, the program will only print out a student's name if the name you look up during your nth search matches the student in exactly nth object in the array.

3 Answers

I'm not 100% sure what you're asking. Your explanation is correct, as far as it goes.

So, in the code running, step one i==0, Dave !==Jody. so the if loop doesn't run. Then step two, your code goes back to your for loop, where i ==1. we will say that student[1] === Jon. in that case, Dave!== Jon. so the if loop doesn't run. then step three, your code goes back to your for loop, where i == 2. We will say that student[2] === Dave. In that case, Dave === Jon. then your if loop WILL run.

Is that what you were asking?

Oh my gosh yes. That is exactly what I'm asking, and it just hit me how obvious this actually is! Think it's time for a break.

Thanks Brian!

The loop runs through until it is true. So it runs the loop till your if statement is true, then it implements the code in the conditional statement.