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


#1

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:

undefined
undefined
undefined
undefined

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

// 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) {
    console.log(i.name)
}

#2

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) {
    console.log(family[i].name)
}

hope that makes sense :sunny:


#3

Hey thank you :slightly_smiling: for pointing that out.

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