6. List 'em All!


#1

https://www.codecademy.com/courses/javascript-beginner-en-3bmfN/0/6?curriculum_id=506324b3a7dffd00020bf661#

This code works, so I am able to pass the step, but I don’t think it is working correctly.

var friends = {};

friends.bill = {
    firstName: 'Bill',
    lastName: 'Gates',
    number: '1-208-539-7916',
    address: ['One Microsoft Way', 'Redmond', 'WA']
};
friends.steve = {
    firstName: 'Steve',
    lastName: 'Jobs',
    number: '1-208-421-7752',
    address: ['One Cupertino st', 'Cupertino', 'CA']
};

function list(name) {
    for (var key in name) {
        console.log(key);
    }
}
list(friends); 

The output is:

bill
steve
bill
steve

Two questions:

  1. Why does the output show lowercase names instead of the string in the object?

  2. How does this work? In the for/in loop, I am using a key (that is allowed to be anything, apparently) and the name of the object that is passed into the function through the parameter “friends”. However, how does it know to use just the first name of the object when I am using a word like “key” that is found nowhere else in the app?


#2

because it outputs bill and steve object. which are lowercase. It doesn’t output the firstNames of bill and steve object

yes, because the loop iterator (key in your case) is defined in the loop, it can be anything (but i would be wise to give it a logic name)

then the for in loop assign (in order) all the properties (bill and steve in this case) to the loop iterator

its confusing isn’t it? bill and steve are objects but also properties of friend object, the for in loop does so much work for you, its all most confusing


#3

So, you are saying the return is not the first name, but the name of the object themselves? I think I understand now. I thought of the output as being the first attribute of the object, and was confused on how the function knew to pull the first (and not the second, or third, or all), but it isn’t pulling an attribute of the object, it is pulling the object itself.

That clears it up. Thanks!


#4

Well, i think there is no better way to put it, so it seems you understand :slight_smile:


#5

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