Don't understand how the [key] works


#1

How don’t understand how assigning a random value to [key] the code works.

I also didn’t get how to print that specific set of data (bill).

Thank you in advance.

```
var list = function (friends) {
    for (var firstName in friends) {
        console.log(firstName);
        }
    };
    
var search = function (name) {
        for (var key in friends) {
        if (name === friends[key].firstName) {
            console.log(friends[key]);
           return  friends[key];
            }
    }
} ;

search('Bill');

#2

we don’t assign a random value to key? the for in loop assigns all properties (bill and steve) of object (friends) to key (in order)

so now first key will be bill, so we can get the value of firstName property by doing friends[key].firstName, which is the same as doing:

friends['bill'].firstName

except the loop does both bill and steve (and more if there where more properties to friends), kind of very useful when searching through all entries in friends object


#3

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