Muzzammil Vora Muzzammil Vora - 5 months ago 7
Javascript Question

Javascript object in array Loop

Below is the coding exercise from code academy whose objective is to print out name property. Can you please explain the error and how do i fix it. My code looks like:

// Our Person constructor
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 (var i = 0; i <= family.length; i++) {
console.log (family[i].name);
};
// Now we can make an array of people

// loop through our new array

OUTPUT :
alice
bob
michelle
timmy

---
We're running a test below to make sure your code works.
alicebobmichelletimmy
TypeError: Cannot read property 'name' of undefined

------------------------------------------
Many thanks.

Answer

as in the comments, but to explain the error (so that you learn from the mistake and understand why its causing an error): - you are running a loop that has :

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

This is causing the issue since arrays are zero indexed - meaning that if you have

family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

then you will have the family array of length 4 but its indexed 0 -3.

This means that when you have i <= family.length, you are attempting to find an element with an index of 4 - which doesn't exist and so throws the error.

As mentioned you simply need to remove the = in the for loop and all will be well since i will never get to 4 and will stop at 3 - the highest index in the array.

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