Stuck at Loop the loop in Objects I D:


#1

Hi this is my script which I made for the Loop the loop excercise
I don't know what is wrong with it :frowning:

// 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(i.name);
};

#2

The for statement creates a loop that consists of
- three optional expressions,
- enclosed in parentheses and separated by semicolons,
- followed by a statement or a set of statements executed in the loop.

Syntax

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

Change your [initialization] to var i = 0;
In your [condition] you are checking if i is greater than family.length, that is NEVER going to happen as you initialized i to =zero=
Change your condition into i < family.length ;


#3

In addition, the block of the 'for' loop will not work because your console.log expression will look like this:
first loop: console.log(0.name)
2nd loop: console.log(1.name)
etc.
This, obviously makes no sense. You really want to have this for your expression:
console.log(family[i].firstName)
Then the loops are:
first: console.log(family[0].firstName] --> Alice
2nd: console.log(family[1].firstName] --> Bob
etc.


#4

@steve10brink I have tried using the family[i].name
But it errors again like this

Oops, try again. Make sure to log to the console the name of each object

But looking at the script, I have already put the console.log() function.

Here is what I have done after editing the script according to @leonhard_wettengmx_n and @steve10brink

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

How do I solve this?


#5

in your [condition];will have to be changed in

 i < family.length

and do not forget to use the var-keyword in the [initialization];


#6

Whoa thanks!, But I don't understand one thing, Why do we have to put '<' when we want to say that I should Iterate from 0 until it reaches a point where the value of i is > family's length?

In this case it should be like i > family.length?
I confuse of this little thing.


#7

@udayk8139,

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

You read this as
as long as the number i Value is less-than the family-Array-length
execute { } / Display the =name= property of the object at family-Array-element-i
start with variable i equals =zero=
and after every iteration increment the number Value of i with =one=.

PS.
It is important to use i less than array.length
and NOT use i less equal array.length
as the array.length is the index-nr of the first-non-defined Array-element,
and could be used to =append= a new-element
like
family[ family.length ] = new Person('Uday Kiran',21);