Explain how it works var list = function(friends)


#1


List 'em all!

Code working fine but don't understand something about functions. I have commented the question in the code.


var friends = {
    bill: {
        firstName: 'Bill',
        lastName: 'Thomas',
        number: '01594 456 456',
        address: ['68', ' Abbey', 'Street']
        },
    steve: {
        firstName: 'Steve',
        lastName: 'Thomas',
        number: '01594 458 456',
        address: ['32', 'Trent', 'Steet']
    }
};
//why is friends needed on the line below? I took it out and it still worked fine.
var list = function(friends){ 
    for(var key in friends){
        console.log(key);
        
    }    
}

list();


#2

Hi there.

In this case, you don't necessarily have to have to include friends in the function parameters. The for loop is directly accessing the friends object regardless.

But generally speaking we use functions so that we can reuse them for multiple purposes.

Take a look at the code below, it gives an example as to why you might want to pass parameters to functions instead of hard-coding them like your example has done with friends.

var friends = {
    bill: {
        firstName: 'Bill',
        lastName: 'Thomas',
        number: '01594 456 456',
        address: ['68', ' Abbey', 'Street']
        },
    steve: {
        firstName: 'Steve',
        lastName: 'Thomas',
        number: '01594 458 456',
        address: ['32', 'Trent', 'Steet']
    }
};
// Our second object which contains some acquaintances.
// We will iterate over these just like the above!
var acquaintances = {
	mary: {
  	firstName: 'Mary',
    lastName: 'Anne'
  },
  jane: {
  	firstName: 'Jane',
    lastName: 'Doe'
  }
};
/* 
Instead of narrowing our naming convention down to just friends,
Lets instead give our reference variable a more generic name like.. aList
aList is now the name given to any list we pass to this helpful function.
Remember aList is just a placeholder name and holds no other meaning outside of the function.
*/
var list = function(aList){ 
    /* Here instead of iterating over the friends directly, we iterate over our list that
    we passed in our function parameter */
    for(var key in aList){
        console.log(key);
        
    }    
}
// Now we can use the function for more than one purpose.
// Here we use list to print our friends and acquaintances.
list(friends);
list(acquaintances);

Hope that clears it up for you.


#3

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