6 Why does this work?



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) {

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) {


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


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:

//^ 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.


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