The use of the "i" variable in "for" loops


#1

Why do I have to use the "i" variable in my "for" loops, instead of the actual variable I named itself? For instance in the example below, why can't I just use the variable "cities"?


//Why does this work..
var cities = ["Melbourne", "Amman", "Helsinki", "NYC", "Miami"];

for (var i = 0; i < cities.length; i++) {
    console.log("I would like to visit " + cities[i]);
}
//..but this does not?
var cities = ["Melbourne", "Amman", "Helsinki", "NYC", "Miami"];

for (cities = 0; cities < cities.length; cities++) {
    console.log("I would like to visit " + cities);
}


Thank you.


#2

You don't have to use the i variable. i just stands for "index" and the index can be labeled a b c d dog cat deezenuts whatever you want.

You just can't name it the same var that your ...matrix? I forget...shiz...that thing with the [ ] whatever it's called. lol.

Melbourne has an index of 0, amman i=1, Helsinki i=2, etc.

This information is INSIDE of cities. cities does not = 0. cities = your array (that's the word).

If you are using a for loop to cycle through the index (or place) of your cities array you need to use a different variable to slot into cities[i]. The [i] just stands for the number in the list that is your array that represents whatever the value is.

I hope that made sense. I'm not sure if I did a good job explaining it.


#3

Perfect, I don't think you could have explained it any clearer, thanks I understand now.


#4

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