4. Iterating over an array


#1


https://www.codecademy.com/courses/javascript-beginner-en-9Sgpi/0/4?curriculum_id=506324b3a7dffd00020bf661#


i dont know why this code isnt working .please help.


var languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby"];

for (var i = 0; i < languages.length ; i)
{
    console.log(i++);
}


#2

Hi the i++ should be inde the for loop statement and not in console.log() so where you put

for (var i = 0; i < languages.length ; i)

i in the last part you should put i++ and in the console.log() put i


#3

it still does not work


#4

here is my code

var languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby"];

for (var i = 0; i < languages.length ; i++)
{
    console.log(i);
}

#5

then this line

console.log(i);

you should log the item inside the array languages so you should do it like that

console.log(languages[i]);

#6

it works thanks

here is the last code

var languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby"];

for (var i = 0; i < languages.length ; i++)
{
    console.log(languages[i]);
}

#7

Hello,

Can you explain what is actually happening inside this for loop? I'm having trouble understanding the necessity of this particular exercise.


#8

var languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby"];
                   0       1          2           3        4
for (var i = 0; i < languages.length ; i++)
{
    console.log(languages[i]);
}

Loop runs the same amount of times that the languages array is in length:
languages.length = 5
→ loop runs 5 times.

Each time it runs, it logs a different value to the console, from the array. Each time it increases the index number it's logging from:
first loop, first item - HTML
second loop, second item - CSS
etc.

for (var i = 0; this starts at 0 because it's as long as i is less than (<) languages.length, which is 5. It runs as long as i is less than 5, so it goes:
i = 0 → console.log(languages[0])
i = 1 → console.log(languages[1])
i = 2 → console.log(languages[2])
i = 3 → console.log(languages[3])
i = 4 → console.log(languages[4])

Any questions?


7. Search for a friend
#9

That makes sense, but why is the i++ necessary here?


#10

To increase the number every time:
i = 0 → console.log(languages[0])
i = 1 → console.log(languages[1])
i = 2 → console.log(languages[2])
i = 3 → console.log(languages[3])
i = 4 → console.log(languages[4])
                                                             ^
That one.


#11

Got it, this is a little more confusing than the original "for loop" that was introduced where there's no array like below:

for (var i = 100; i >0; i -=5) {
console.log(i); } .. it's easy for me to understand the use of this and what it's doing while this particular example seems like it's extra work to print a few words

The array makes it more challenging. I'm completely new to this stuff so thanks for your help.


#12

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