Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

5 Answers 5

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.

share|improve this answer

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

share|improve this answer
    
its fixed, thanks! and thanks for the quick reply! –  user1877731 Aug 22 '13 at 14:55
    
Welcome. If it solved your problem, you can mark it as an answer also. –  Nicolae Olariu Aug 22 '13 at 15:03

What about i < family.length?

share|improve this answer

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

share|improve this answer

It works just fine.

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

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.