6 Why does this work?


#1


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


This code is correct, but I'm not sure exactly why it works. My question is about the list function. Why don't we reference the friends object or the firstName parameter by name in the function? For example:

var list = function(friends) {
for(var firstName in friends) {
console.log(firstName);
}
};


var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "(206) 555-5555",
        address: ['One Microsoft Way','Redmond','WA','98052'],
    },
    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "(212) 555-5555",
        address: ['1200 Park Ave','Emeryville','CA','94608'],
    },
};

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


#2

You don't reference it because in the function you're making it to work with any "obj" not just "friends".

e.g.,

you could also call list upon the following:

var foo = {
   bar: { test: 3},
   ya: { test: 2} 
};

See, when we actually call list, it would look like this:

list(friends);
//^ the above will pass friends into list as a parameter.
// meaning once we're in list obj = friends, so we can read list as 
// for(var prop in friends) {console.log(prop); }

the for will loop over every item within "obj", since you passed in friends as your version of "obj" we look over all the items within friends.


#3

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