List 'em all!


#1

Hi I don't quite understand what's going on in this code:
var friends = new Object ();

friends.bill = new Object();
friends.bill.firstName = 'Bill';
friends.bill.lastName = 'Gates';
friends.bill.number = '555-555-5555';
friends.bill.address = ['1835 72rd AVE NE', 'MEDINA', 'WASHINGTON', '10225'];

friends.steve = new Object();
friends.steve.firstName = 'Steve';
friends.steve.lastName = 'Jobs';
friends.steve.number = '666-666-6666';
friends.steve.address = ['2101 Waverly Place', 'Palo Alto', 'CA', '94301'];

function list(obj){
for(var prop in obj){
console.log(prop);
}
}

I don't quite understand HOW the function list prints out the things it does.


#2

prop gets assigned each property in your friends object.

you can read more about for in here

simply supply friends object as argument when calling the list function


#3

Ok. But how does it know?
How does it know that obj in this case refers to my object?
I could change obj to poop and it still comes out with the same.


#4

it doesn't, yet. You need to call the function and supply an argument:

function list(obj){
for(var prop in obj){
console.log(prop);
}
}
list(friends)

Now the parameter (obj) knows what to deal with, until that time obj is basically just a placeholder.

i wouldn't use the same name for the function parameter and loop iterator, you might get away with it, but its risky


#5

Am I understanding this right?

function list(obj){ //here we create a function to call with a changeable parameter---list(friends);
for(var prop in obj){ //we create a variable that cycles through the changeable parameter that is being input during the call
conlsole.log(prop) //when calling, print out the variable called prop
}
}
list(friends);//prints out the names


#6

yes, you are understanding it right :slight_smile:

you could even supply bill or steve as argument:

function list(obj){
for(var prop in obj){
console.log(prop);
}
}
list(friends)
list(bill)
list(steve)

not the point of the exercise, but still possible. it will give you all properties of whatever object you supply as argument


#7

you mean
list(friends)
list(friends.bill)
list(friends.steve)
?


#8

Yea, you are right. Well, it does prove (even though i made a mistake) that you understand it well, given you corrected me :slight_smile:


#9

Thanks for your help


#10

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