Question #6: Not sure what is wrong with my code


#1

var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "hines",
number: "(626) 602-5823",
address: ['14901 New Vista Place','Hacienda Heights','CA','91745']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "(323) 225-5997",
address: ['2091 Stonehurst Drive','Rialto','CA','90033']
};
var list = function (friends) {
for (var firstName in Friends) {
console.log(firstName)
}
};

Can someone please tell me what i'm doing wrong? Thanks!


#2

var firstName in Friends ?

it should be lowercase.


#3

oh wow, thanks for pointing that out!


#4

np, although I ran it and it worked fine. Is the lesson not allowing you to pass?


#5

It's working for me now, thanks again!


#7

When choosing variable names we can make things more readable if we don't use multiple references. Consider:

var list = function (object) {
    for (var key in object) {
        console.log(key);
    }
};

The friends object consists of primary keys (direct properties), bill and steve, each of which have values that are also objects, each with a firstName property. This variable is best only used to reference this property, and not as a dynamic iterator.

The above function is written as a generic piece of reusable code that can be given any object reference and it logs all the primary key names.

    list(friends);
    /*
    bill
    steve
    */

for..in statements are object enumerators. But they are limited to one context layer. To iterate over nested properties, takes nested for..in statements. In the above, we could only list the primary keys (meaning first layer). Consider the following for listing all the keys, in both layers:

var listKeys = function (object) {
    for (var key in object) {
        console.log(key);
        for (var prop in object[key]) {
            console.log(prop);
        }
    }
};

Now the list contains,

    listKeys(friends);
    /*
    bill
    firstName
    lastName
    number
    address
    steve
    firstName
    lastName
    number
    address
    */

There's more practice ahead...

A word about reference objects, which term applies to objects, arrays and functions. They are not copied into function scope; they are threaded to it as a reference. When the parameter of a function is a reference object, that object is global from the standpoint of the function.

It's for this reason that a generic function wins out over a dedicated one. When we use a parameter name in a function that matches the object being passed in, the function cannot be used by any other object. It becomes non-reusable, or dedicated. That's why it's a good idea to choose variable names prudently, and give them some meaning as to their purpose in the program. This too will come up a lot as we progress, be sure of it.