Why do we need "[i]" in family[i].name in for loop?


#1


https://www.codecademy.com/en/courses/spencer-sandbox/4/2?curriculum_id=506324b3a7dffd00020bf661


My code is working fine, but I do not understand this. Why do I need to put "[i]" in this for loop?


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


#2

I'll walk you through this step by step :slight_smile:

1.Person Constructor

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

In the Person Constructor we have two different properties.
A name and an age.

2.Create Empty Array
"Arrays filled with objects will work just like arrays filled with numbers or strings."

// Now we can make an array of people
var family = new Array();

3.Put FOUR Objects inside our family 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);

This is where we store the different objects inside of our array.
The family array with the elements [0],[1],[2],[3] is basically how we locate where our objects information was stored, if ever we want to use this information again in our project.

4.How to access our arrays that contain the different Objects.

// loop through our new array
for (var i = 0; i<family.length;i++)
{
    console.log(family[i].name);    
}

As we follow along in to code we see in our for loop: var i = 0; which initializes our counter variable to 0.

The i<family.length; is looked at as the conditional statement that's tested every iteration of our code, as long as out condition is true the statements inside of our for loop will continue to iterate.

The length property returns the length of our family array (which is 4).

i++ is the accumulator, it'll add 1 every time the for loop runs.

In order to access our different arrays that contain Objects we MUST use the different indexes, which is why we put [i]. Otherwise the program would print out undefined. The [i] specifies which array you would like to get information from.
For example:

  • family[0].name will print out "alice".

  • family[1].name will print out "bob".

Once again the [i] specifies which array that contains objects you would like to get information from.


#3

Thank you very much for the detailed explanation. Especially the last part about the "i" holding the place for 1,2,3,4


#4

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