6. List em all, why is my code working?


#1

Hello everyone, i have a quick question: my code works but i don't understand it

var friends = new Object();

friends.bill = {
    firstName: "Bill",
    lastName: "Gates",
    number: "123555555",
    address: ['One Microsoft way', 'Redmond City', "WA", "98052"]
};

friends.steve = {
    firstName: "Steve",
    lastName: "Jobs",
    number: "456555555",
    address: ["One Cupertino Ave", 'San Francisco', 'CA', "92210"]
};

var list = function(y) {
    for (var x in y){
     console.log(x);   
    }
}

My question is simple : How does the function LIST knows that it should ONLY print Bill and Steve and not every key? And how does it even know that it has to search in the previous objects?

Many thanks for your hindsight
best
Pierre


#2

Hi @el_cortez,

Assuming you call list like list(friends):

Well, the friends object has only two keys - "bill" and "steve", and the list function prints only those two. It would not iterate over the keys of the objects held by "bill" and "steve" keys, for that you need an additional for-in loop.

I'm not sure if I understand "previous objects", but the list function will list the keys of the object that you supplied it as an argument while calling it as list(your_object). So, you can also do this:

var my_object = {
    "cars": 1,
    "bikes": false,
    "scooter": [1, 2, 3],
    "any?": {
        "nested" : 1,
        "nested2": 2
    }
}

list(my_object);

outputs:

cars
bikes
scooter
any?

#3

Thank you, I understood. The exercise worked even without calling the function, that's why I was confused. it makes more sense now.


#4

I'm still confused, possibly for the same reason you were confused. Does the exercise call "list(friends);" on its own? The keys "bill" and "steve" print out without my calling the function with the "friends" parameter. That's confusing. Maybe I wouldn't want to use the function that way. For instance, if I wanted to print the keys in the "bill" object I would call "list(friends.bill);" (which prints "firstName", "lastName", etc).


#5

I got it, the SCT calls your list function internally to make sure your code is working appropriately. I agree it should put some line like: "The following output is generated by the SCT" or so and so so that the users aren't confused.

Hope that helps! :slightly_smiling: