Why cities.length?


#1


loops and arrays 1
step 11

I don't have a problem with the code. What I am trying to do is get a little better understanding by seeing if hearing this from another person might help. What does using the .length after cities in this example do? Why is it necessary, I guess I don't know what the point of it is. I know what .length does but am not sure why it is used for this example.


var cities = ["Melbourne", "Amman", "Helsinki", "NYC"];

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


#2

i think i figured it out.


#3

Arrays are zero-indexed, meaning the first element is at index [0]. That's why the initial value is set to 0. The length of the array will always be 1 more than the last index, hence, < array.length, and not <=.

cities.length === 4

for (var i = 0; i < 4; i++) {}

If we write a for loop like the above, it is fixed. When we use the array.length in the condition, it is dynamic and the length doesn't have to be known by the programmer.


#4

thank you for this, this helped me make sense of what is going on, I appreciate it.


#5

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