List them all! How does for/in loop know which object to access?


#1


When executing the below code, i get "bill" and "steve" as output.
I defined a new object "tests" with another two objectes "bill12" and "steve12".

How does my list function even know which object to access?
what if i wanted to print out "bill12" and "steve12"

Can someone explain a little more?


var friends = new Object();
friends.bill = new Object();
friends.steve = new Object();

var tests = new Object();
tests.bill12 = new Object();
tests.steve12 = new Object();

var list = function(abc){

    for(var xyz in abc)
    {
        console.log(xyz);  
    }
}

EDIT:
I copied this code to another lesson, where it does not output anything.
At this point im not even sure what i should think... Probably forget about this post, i don't know how to delete it


#2

No, don't forget about this topic, it is important. Lets take a step back, if we have a function which has a parameter:

var example = function(cde){
   console.log(cde);
}

we can call the function, which we give an argument, so then the parameter has the value of the argument passed:

var example = function(cde){
   console.log(cde);
}
example("lets see how this works");

so now with your list function, you can call it by passing the object as argument:

list(friends);

or:

list(tests);

the reason you saw output in the original lesson, was because behind the scenes codecademy did the function call for you, for validation purposes.

Where as in a different exercise, this is not the case, you have to call the function manual if you want to execute it

Hope this helps :slight_smile:


#3

Aaaaah, okay that sentence cleared all up for me:

So the lesson always calls function "list" with parameter "friends", thats why always "bill" and "steve" is printed out.

Good to know, thank you very much!


#4