12. Contact List for loop function


#1


How does the function for the for loop work here?
I am trying to understand why the phrase (var search) can be replaced by var (dogs/cats/key/x/etc) and the console still returns the contact details when the function is called.


function search(name) {
    for (var search in friends) {
        if (name===friends[search].firstName) {
            console.log(friends[search])
            return friends[search]

Replace this line with your code.


#2

Because, when you define the the for in loop:

for (var search in friends)

you define the iterator (search in your case) inside the for in loop. Whatever you name your iterator will gets assigned the values (in order), the for in loop will take care of this for you


#3

Right, I think I am slightly clearer now. Thanks for your help! Reading your replies in other question threads also helped me a lot.

Cheers


#4

MDN (mozzila developers network) also always has great documentation, including for in loop. You can also read that if you want.

Good that this is a bit clearer now :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.