I am currently doing the Codeacdemy tutorials on Javascript and while doing the Object tutorial I came I keep getting undefined for the following:
// Our Person constructor
function Person (name, age){
this.name = name;
this.age = age;
}
// Now we can make an array of people
var family = [];
family[0] = Person("alice", 40);
family[1] = Person("bob", 42);
family[2] = Person("michelle", 8);
family[3] = Person("timmy", 6);
// loop through our new array
for(var person in family){
console.log("name: "+person.name);
}
I have had issues with codecademy before so I tried it in my own webpage and still get undefined. Can anyone explain why to me. I have also tried using family[0].name and that is undefined too
for-in loops return the index, not the value. If you change that to console.log("name: "+family[person].name), it will work as expected.
for(var person in family){
console.log(person);
console.log("name: "+person.name);
}
0
name: undefined
1
name: undefined
2
name: undefined
3
name: undefined
As @basilikum also mentioned, you'll need to create each person with the new keyword, otherwise they won't be an object.
console.log(Person("alice", 40)); // undefined
console.log(new Person("alice", 40)); // Person {name: "alice", age: 40}
You need to create your objects using the new keyword:
family[0] = new Person("alice", 40);
Person is just a function. If you call it, you receive whatever this function returns. Since it doesn't return anything, all your entries are undefined. By using new, you are calling this function as a constructor, which creates an new objects with your defined properties and returns that object instead.
As SpenserJ said, you also have to keep in mind, that the for loop only returns the key and not the actual object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With