0

Here is my code

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

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);

for (i =0; i<= family.length; i++) {
    console.log (family[i].name);
}

This produces an error: TypeError: Cannot read property 'name' of undefined

Can anyone point me in the right direction from here?

5 Answers 5

3

You're iterating one too far.

for (var i = 0; i < family.length; i++)

JavaScript arrays start at zero, and the last non-empty cell is at length - 1. Thus you have to stop iterating when your index is equal to the length, not when it's greater than the length.

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

Comments

2

You should change your test condition to i < family.length, you're getting out of bounds.

1 Comment

Welcome. If it solved your problem, you can mark it as an answer also.
1

What about i < family.length?

Comments

1

Change <= to <. You are exceeding the array limit.

Comments

0

It works just fine.

for (i =0; i<= family.length; i++)

demo: http://jsfiddle.net/285Th/1/

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.