6. List 'em all!



I do not understand the for...in function, and what it is used for. It's very frustrating to have a totally new concept thrown in haphazardly during the instruction of a lesson. Can somebody please help me understand what the for...in function is doing and why we are using it?

What I have below, but I don't understand the concept or what we are trying to achieve with this function, please help.

var friends = {}
friends.bill = {
    firstName: "Bill",
    lastName: "Brasky",
    number: "(908) 987 7363",
    address: ["27 Paya Lebar Square", "Singapore", "SG", "409042"]
friends.steve = {
    firstName: "Steve",
    lastName: "Segal",
    number: "(870) 876 3736",
    address: ["120 St. Albans Dr", "Raleigh", "NC", "27605"]

var list = function(friend){
    for(bill in friends);


the problem with the for .. in loop is that it does all the work for you, which is confusing. the the for in loop will loop over all properties inside your friends objects, and (in turn) assign the values it find in the friends object to the variable (in this case bill, you could name this variable anything)

so lets say we have:

var list = function(friends){
   for (friend in friends){

this will log bill (bill the object, not the firstname) and steve to the console.

lets make a comparison with an array:

friends = ["bill","steve"]
for (i = 0; i < friends.length; i++){
   friend = friends[i]

i tried to use the same variable names as in my first example. What the for in loop does for you is determine the start position, the length and the increment. then it assigns the values to friend, this is all done for you.


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