var names = ["Ringo", "John", "Paul", "George"];
for (var i = 0; i < names.length; i++) {
alert("Say hello to " + names[i]);
}
In the code above, I assume it’s the last piece (names[i]) that’s making the index of the array change to give me the correct name. Is this true? What exactly is going on? What’s making the index change so that it will change the name? And if I were to use another label for the variable, say ‘a’, or ‘b’ or even ‘counter’, instead of ‘i’, would it still work?
The first part
var names = ["Ringo", "John", "Paul", "George"];is your array definition. You are loading a JavaScript array with 4 items. Their indices in the array are as follows:
To refer to those items individually in JS, you would do this:
The
forloop in your code steps through each item in the array.var i = 0says that we’re creating a new variable to use as the index of the array. This could just as easily bevar a,var b,var indexOfTheArray. Whatever.The next part
i < names.lengthis a condition that causes theforloop to repeat until it is met. In this case it says “loop as long as the value ofiis less than the length of the arraynames“.array.lengthgives the total number of items in the array. Sonames.lengthwould equal 4.The last part is a special JS command
i++. This says “add 1 to the value ofi“.Everytime the
forloop reaches the closing bracket, it incrementsi, and evaluates the condition.Inside the loop,
irepresents the current index of the array that you’re working with.You can use
names[i]as many times as you want in theforloop and it will not change until the next time you reach the end bracket and it loops back around. Theniwill increment and you’ll have the next value in the array.