This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Peter Benjamin
almost 11 years

TypeError: Unable to get property 'name' of undefined or null reference

My code is the following:

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

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

But, I receive the error message:

TypeError: Unable to get property 'name' of undefined or null reference

Any ideas?

Answer 51bbd3e08c1ccc4d220073b0

0 votes

Permalink

I looked through your code and it seems that when you posted the for method you forgot to add var before i =0, but the weird part is that I took your code, put it into the codecademy lab’s site and it worked perfectly. I’ve noticed sometimes when i’m using codecademy, and I post code, sometimes it says it’s wrong, and so I reset the code and I place the same peice of code that I put in before and suddenly it works. Here is a correct variation:

Person = function(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);
    
    // loop through our new array
    for(var i = 0; i<family.length; i++){
      console.log(family[i].name);
    }
points
Submitted by Gamma
almost 11 years

5 comments

Gamma almost 11 years

Plus forgetting the var should have given you an error I’d assume, but I’m not quite sure. I hope this helps.

Peter Benjamin almost 11 years

I tried placing the “var i;” after the Person constructor block, but still no luck. I will try to reset the code and re-attempt it. Thank you.

Peter Benjamin almost 11 years

I reset the code, re-attempted, but still got same error.

Gamma almost 11 years

Did you put the code in my post? Or did you put your old code back in?

jasoncdu over 10 years

Gamma the instructions asked for constructor but the way you set it up with

“Person = function(name, age) {

vs what we learned from before: function Person(name,age) {

.. I get the same error if I do it with a constructor but with your way it works .. and every other code is the same beside line 1

Answer 51d2c8b852f863c46000b4ae

0 votes

Permalink

I had the same error, but for a different reason.

I was looping one increment too much in the for loop:

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

It should be:

for (i = 0; i < family.length; i++) {
    console.log(family[i].name);
}
points
Submitted by ultraLimitem
over 10 years