Why can't I use for(var i in ...) instead of for(var i =0; i < family.length; ...)


Hi all,
I was just wondering why I can't use a for(var i in family) type of for loop instead of for(var i = 0; i < family.length; i++) type. I feel that the former one is more elegant. I don't know what's wrong in writing like that, because I get an error:


We're running a test below to make sure your code works.

// My Code
// Our Person constructor
function Person(name, age) {
this.name = name;
this.age = age;

// Now we can make an array of people
var family = Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

// loop through our new array
// for (var i = 0; i < family.length; i++) {
//     console.log(family[i].name);
// }
for(var i in family) {


Actually this would work

i is just the count however, so you were literally saying 1.name, 2.name which would be undefined :slightly_smiling:

You want to do family[0..1..2..ect].name accessing the 0th element of the family array, to do that, just add family and some square brackets around i.

for(var i in family) {

hope that makes sense :sunny:


Hey thank you :slightly_smiling: for pointing that out.

I was working on python earlier, so, you can guess :slightly_smiling: