Introduction to Objects I (27/33)


#1

Here is my code
`// 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]);
};`

And here is the output i get:

{ name: 'alice', age: 40 }
{ name: 'bob', age: 42 }
{ name: 'michelle', age: 8 }
{ name: 'timmy', age: 6 }
undefined


We're running a test below to make sure your code works.
{ name: 'alice', age: 40 }{ name: 'bob', age: 42 }{ name: 'michelle', age: 8 }{ name: 'timmy', age: 6 }undefined

I passed the test and all but since the task was to print (maybe)only the names, i couldn't figure out the way to do that.
If i replace console.log(family[i]) with console.log(family[i].name) in the "for" loop, i get a error message like that: "TypeError: Cannot read property 'name' of undefined"

Can anyone help me with printing out only the names in this case?

Thanks!

Markus Kuusmann


#2

@markus.k,

1

for ([initialization]; [condition]; [final-expression]) {
   statement
}

[your output]

{ name: 'alice', age: 40 }
{ name: 'bob', age: 42 }
{ name: 'michelle', age: 8 }
{ name: 'timmy', age: 6 }
undefined

[end-of-your-output]

The cause of the undefined
is in the condition of your FOR-loop
where you are using the less equal operator.....
this should be the less than operator.

Reference

== the Book ==
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

== discussions / opinions ==
javascript array site:developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators

== guidance ==
www.crockford.com
http://javascript.crockford.com/survey.html
http://javascript.crockford.com/code.html <<< Javascript coding conventions


#3

Thanks!
I got it now, i tought that i already tried this version and it didn't work.
Thanks again!