Reason for Loops and Arrays


#1

It might be a daft question, but is there a reason behind using both a loop and an array?

I understand the concepts separately for a loop and an array. I see 'loop' as saving on repetition and an array allowing me to save more data than just one variable.

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

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

Couldn't I just use the console.log as above and save having to enter the extra line of code ?

Kind regards for those who help on my learning journey :smiley:


#2

You use a loop so it repeats the console.log statement, otherwise if you removed the loop and just had

console.log("I would like to visit" + cities);

it would print out

"I would like to visit Melbourne,Amman,Helsinki,NYC"

whereas the loop does
I would like to visit Melbourne.
It would then print this for Amman and on untill it reached the end of the array


#3

I see, thank you, I believe I understand it better now.

I think I got mixed up on the transcript saying it is for if you have, say more than 100 elements in your data list. I was thinking why add the extra line and not use the standard Array as mentioned in the previous exercise. when for this exercise it is getting us to repeat the phrase so each city is listed, under each other.

Thank you again.