Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

jawad malik
jawad malik
827 Points

Hello. Im totally confused about this index position.Can anyone help?

var students=['sasha', 'lynn', 'jenifer', 'paul']; for(var i = 0; i<students.length i+=1) console.log(students[i];

should the last part not be

console.log(students[0];

since its supposed to iterate from index postiton o. what is the meaning of [i]

2 Answers

nico dev
nico dev
20,364 Points

Yes, I totally remember having that confusion too when I started :)

One way to look at it is this: OK, let's try both ways and see the difference, and there you will see what each one does.

Try this on your browser's dev tools (in the Console tab):

**** NOTE: **** You will need to be very careful with the syntax (every semicolon, bracket, etc. is important, otherwise you'll just receive errors and errors)

var students = ['sasha', 'lynn', 'jenifer', 'paul'];
for(var i = 0; i<students.length; i+=1) {
    console.log(students[i]);
}
// This will output: 
// sasha
// lynn
// jenifer
// paul

Now, try this:

var students = ['sasha', 'lynn', 'jenifer', 'paul'];
for(var i = 0; i<students.length; i+=1) {
    console.log(students[0]);
}
// This will output: 
// sasha (and then a four somewhere aside)

What that four aside means is that sasha was printed four times.

Summary:

  • The index 0 will always be the first one in the array, no matter how many times you loop.
  • The index i will increase by one every time, and then it will be one time each item in the array (first it will represent the item 0, then the item 1 and so on until the end you set for the loop).

'i' represents the index value of each item in an array. Since an array is zero-indexed, you store the numeric value of 0(zero) when declaring the variable 'i' in the for loop(var i = 0). Keep in mind that the value of the variable 'i' will increase by 1 every time the loop runs(i +=1) till it is just below the length property of the given array(i < students.length). So 'i' will be 0, 1, 2 and finally 3 i.e. students[0], students[1], students[2] and students[3], logging each iteration in the console of the browser.