FAQ: Loops - Looping through Arrays

If you do with backticks it gives an error, a slight bug to resolve

I made a mistake in writing this code, but it worked anyways, and now I’m trying to figure out why it worked.

I wrote:

const vacationSpots = [‘Bali’, ‘Paris’, ‘Tulum’];

// Write your code below

for (i = 0; i < vacationSpots.length; i++){

console.log(I would love to visit ${vacationSpots[i]})

};

I forgot to define ‘i’ as a variable using ‘let’. My code still cycled through all of the information in the array, and printed properly, but the exercise did not count my answer as correct. Why would this still work if the console did not know to define ‘i’ ?

It still works because i gets declared in global scope which is accessible in the loop body. We do want to avoid writing loops like this, especially inside a function. If that subject has not come up, then it will soon enough, along with the subject of scope.

The code above is written in the global namespace, so the variable will persist in memory. By declaring the variable with let we confine it to the loop’s code block so that once the loop is finished, the variable no longer persists in memory. This is the desirable approach to keep our global namespace free of unused variables.

1 Like

Hello Everyone! There is something I don’t understand in this lesson and I was wondering if you could please help me understand it:

To loop through each element in an array, a for loop should use the array’s .length property in its condition.

Check out the example below to see how for loops iterate on arrays:

const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion'];for (let i = 0; i < animals.length; i++){  console.log(animals[i]);}

This example would give you the following output:

Grizzly BearSlothSea Lion

Based on what I read from the arrays lectures about the .length property, it is only supposed to give the length of the array (which means 3). But in this for loop example, why does it display the 3 elements underneath each other instead of the number of elements within the array like it is supposed to?

And also, can somebody please explain what does this mean? - " Remember that arrays are zero-indexed, the index of the last element of an array is equivalent to the length of that array minus 1. If we tried to access an element at the index of animals.length we will have gone too far!"

  • the first sentence I understand as it is referring to array elements being identified using their respective index number, but what does the 2nd sentence mean? How can you even 'access an element at the index of animals.length? Can you even do that? How does it go too far? And why?

Thank you very much respectfully for your time and sorry, but I am autistic and struggle with handling something that has 2 opposite logics.

Only if we need to change the value at a given index. To READ ONLY the values, without changing them, use,

for (let x of animals) {

}

Much simpler to read and debug.

Because each one is logged separately. console.log() does not keep the draw pencil on the same line, but injects a newline at the end.

If an array has length, 7, then array[7] does not exist. 7 is said to be out of range. If we try to log array[7] we get, undefined.

Sorry, I still don’t understand. I still don’t see the connection between these notions together.

Only if we need to change the value at a given index. To READ ONLY the values, without changing them, use,
for (let x of animals) {

}

Why use this method of writing instead? And shouldn’t .length only say how many elements are there in an array? Why does it display them one by one?

Ok, so now I have fond a new logic pattern to these loops and made it more linear for my style of learning. Could anybody please check to see if what I wrote in my comments is correct? Thank you very much!

const vacationSpots = [‘Bali’, ‘Paris’, ‘Tulum’];

// Write your code below

// This loop will start with index being equal to 0 and then the stopping condition will run as long as index is less than the length of the array list in vacationSpots.

for (let i = 0; i < vacationSpots.length; i++) {

// This will print out each each element within the array by using the vacationSpots[i] declartion next to the string concatenation and it can be done the same using string interpolaion.

console.log('I would love to visit ’ + vacationSpots[i]);

}

And index (i) is what causes the repetition to display the 3 cities in the console.

1 Like
const vacationSpots = ['Bali', 'Paris', 'Tulum','Thailand'];

// Write your code below
for (let i = 0 ; 1 < vacationSpots.length; i++ ){
  console.log('I would love to visit ' + vacationSpots[i]);
}

why can’t I change the i to a value in the condition ?

A post was split to a new topic: Confused by this

The following is what I have, which I think it’s right. The code runs just fine with correct output, but somehow the system thinks it’s “wrong”. I checked the solution, it’s just another way of solving it. So please take a look:
const vacationSpots = [‘Bali’, ‘Paris’, ‘Tulum’];
for (i = 0; i< vacationSpots.length; i++) {console.log(I would love to visit ${vacationSpots[i]})}

Do you see anything wrong when declaring i?

Yes I do now, I need to use let or const at front. this begs a further question, since I did not use const or let, why did the code still run without giving error message? in the console log, FYI, somehow the ` mark can be not displayed in this message board but it’s there in my code

You actually do use a declaration for the variable in a loop.

I saw its just because you didn’t format it properly. Learn how to in this topic: [How to] Format code in posts

for (i = 0; ...; ...) {}

for (let i = 0; ...; ...) {}

In the first example, i is defined, not declared. In the second, it is declared and defined.

The defined variable not only leaks out of the code block, but out of the function too since it gets declared in global scope. This is something we are repeatedly warned against: “Do not pollute global scope.”

2 Likes

so what I hear you saying is, if I don’t use let or const to declare the variable, even if I do so inside the for loop, it will “leak out” of the code block and function and become a global variable. hence the problem of pollution of global scope. Am I right?

1 Like

Really, i < animals.length means that the loop will continue UNTIL i becomes GREATER than animals.length.