1

Here is the code:

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

// Now we can make an array of peoples
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++; ) {
    console.log(family[i].name)
};

The expected output of this script is:

alice
bob
michelle
timmy

But the output is:

Uncaught TypeError: Cannot read property 'name' of undefined (anonymous function)

3 Answers 3

2

Add a new keyword for each Person added, and remove the extra ; in the for-loop (after the i++)

// Now we can make an array of people
var family = new 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 ( i=0; i < family.length; i++ ) {
    console.log(family[i].name);       // Also, added a semicolon here. Not required, but it's good practice to close your lines.
};

This will now log:

alice
bob
michelle
timmy

Sign up to request clarification or add additional context in comments.

Comments

0
// 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] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

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

1 Comment

This is correct, but you should add some comments about what you changed and why.
0

I did something like this:

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

// Now we can make an array of people
var family = new 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 famloop in family) {
    console.log(family[famloop].name);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.