27. Loop the loop help


#1

link to the lesson
https://www.codecademy.com/en/courses/spencer-sandbox/4/2?curriculum_id=506324b3a7dffd00020bf661#

this appears on the console,
"alice
bob
michelle
timmy


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

Code

// 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(i=0;i<=family.length;i++){
    console.log(family[i].name);
    
    
    
}

I have no idea what is causing this problem!
please help.


#2

Hello @coursepro35324,

change your i <= family.length to i < family.length, because if i makes to family.length, then there won't be an item to iterate over, since array indices are always array.length -1. Hope you understand now...


#3

I cannot find my error. It says: SyntaxError: missing before statement

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

// 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, iconsole.log(family[i].name)
};


#4

Hello @gigasurfer34739,

Your problem lies in the fact that you haven't written the syntax for your for loop correctly. Just a refresher on the syntax of the for loop...

for(initialization; condition; update) {
    //Some Code!!
}

So, in order to loop over numbers 1 all the way unto 10, I would use the following...

for(var i = 1; i < 11; i++) {
    //Some Code!
}

Hope this fixes your problem...


#5

Thank you. So it was just changing coma for semicolon?


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.