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

Arrays and for loops in javascript

Just doing a bit of a refresher on arrays and for loops. just so I understand;

var myArray = ["bread", "coffee", "milk"];

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

so [i] makes its way through the length of items in the array - so once you want to access all the information within the array, you use the [i] as the index position. Just like you would if you wanted to retrieve a single item

So, is this correct thinking? basically all items have a shared index value of [i]?

var myArray = [
 "bread", //[0][i]
 "coffee", //[1][i]
 "milk"  //[2][i]
];

1 Answer

I would be careful with [0][i] because that looks like a two-dimensional array. Basically, i is a placeholder for numbers 0 thru 2 here and in each iteration of the loop i assumes one of those values. So, myArray[0] refers to the first item in the array, which is "bread", myArray[1] refers to the second item in the array, which is "coffee", and myArray[2] refers to the third item in the array, "milk".

Hey, thank you for getting back to my question. Yes, absolutely. I didn't mean to cause confusion. I only included the [i] to show that each item in the array has been passed by the [i] variable. Not to create a two dimensional array.