27/33 (problem with syntax)


#1

I am so sorry to post again, but I am so stuck --

// 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(); 
    var family[0] = new Person ("Alice", 40);
    var family[1] = new Person("Bob", 42);
    var family[2] = new Person("Michell", 8);
    var family[3] = new Person("Timmy", 6);
    
    // loop through our new array
    
    for (var i = 0; i < family.length; i++) {
        console.log(family[i].name);
    }

Error reads: "SyntaxError: Unexpected token ["

Where is this unexpected token? I feel crazy...


#2

Try this

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

// Now we can make an array of people
}
    var family = []; 
    family[0] = new Person ("Alice", 40);
    family[1] = new Person("Bob", 42);
    family[2] = new Person("Michell", 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);
    }

The problem is family has already been defined so when you say

var family[0] = new Person ("Alice", 40);// meaning you are creating a new variable

well the compiler is expecting family to be a defined array because you are trying to access an index family[0] that's why you get the SyntaxError: Unexpected token [ because you are using the wrong syntax.

Hope it cleared things up.

Ohh ans one more thing you need to close the person class.


#3

All you need to do is take out the "var" in front of all of these statements

var family[0] = new Person ("Alice", 40);
var family[1] = new Person("Bob", 42);
var family[2] = new Person("Michell", 8);
var family[3] = new Person("Timmy", 6);

#4

Thank you for explaining!