27. Loop the loop


#1

// 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 console.log(family[i].person);
};

It keeps saying: 'Oops, try again. Make sure to log to the console the name of each object' Can anyone help me please?


#2

There is no condition provided in the for loop...

I guess this will work

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

A for loop syntax goes this way

for(initialization;condition;incrementation) {

}

#3

Thanks! It works now.:slight_smile:


#4

Glad to help :slight_smile:


#5

Hi, Abhi, strangely when I had a code

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

it won't work :unamused: and when I changed condition to just "<" it worked, can U please explain why so


#6

suppose you are having 5 elements in an array

var myArray = ['one' ,'two' , 'three' , 'four' , 'five'];

while looping through the array, you write

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

the length of the array is 5 , so the value of i will increment like this
0 -> 1 -> 2 ->3 ->4 -> 5 as there is <=.
So it should output 6 elements but since there are only 5 elements so the last line will output undefined.
if we write < then the value will increment like this
0 -> 1 -> 2 ->3 ->4, since 4 is less than 5, So when it reaches the last element i.e index 4 , the loop stops and all 5 elements gets printed.

Hope that's clear to you. I am not good at explaining things. :smiley:


#7

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


#8

Thnx, so simple, I thought sth was wrong with using `
<= instead of < :grin:


#9

No it isn't... it just depends on the initial value of i, and the value at which you want the loop to terminate..


#10

// 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(var key in family)
{

console.log( "Key: " + key + "name: " + family[key].name);
};


#11

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