27 Loop the loop


This is a big ? for me. Think the syntax is alright, but might be mistaken.

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

// Now we can make an array of people
var family = new Array();
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 (i = 0; i < family.length; i++){


Learning to troubleshoot code that isn't doing what you expect is important.

Start by putting in a console.log() to see what the problem is.

How about this first:

var family = new Array();
console.log("family: ", family);

That should get you this out put:

family:  []

That looks nice, just what you would expect, an array has been created and it is empty.

Now try logging the same thing but do it after your code that assigns values to those four elements in your array.

I won't spoil the surprise -- do it and let me know what you get.


Thank you for that quick reply. From what I understand there is difficulty defining the name and age via the Person constructor. An array has been created, but not being filled up with what I want.
Is there anything wrong with my person constructor or how I define the data for each person?

Oops, try again. It looks like the object at index 0 was not created with the Person constructor

TypeError: Cannot read property 'name' of undefined



You've left out the keyword new as you were creating each new Person.


Aww...you spoiled the surprise. Yeah that does it. So even when you define the position in an empty array you have to add 'new'? Is that because it's a new entry to the person contructor?

Thanks a lot!


You need the new because you are creating new objects. Each person is a new object, you just happen to be storing them in an array.


looks right to me. I don't see any syntax issues nor basic grammatical errors. it's exactly what I have and it worked for me.


You have to add new before each person ex:
family[0] = new Person("timmy", 6");


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