Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialnick schubert
3,535 PointsCould someone explain this for loop?
I don't fully understand this for loop, if someone could give me some clarification, that would be great!
I think it works this way:
for (let i = 0; // You create the variable i in the for loop.
i < myList.length; // if the variable i is less than myList.length
i += 1) // add 1 to i
Is this correct? if so, my issue is that I don't think I would have figured this loop out myself.
Thank you!
3 Answers
Lola Jahn
18,718 PointsHey there Nick! You got it almost right.
for (let i = 0; // You create the variable i in the for loop and set it equal to 0
i < myList.length; // the variable i is less than the length of myList (as long as i is less than the length of myList the loop will run)
i += 1) // add 1 to i every time it loops around
Hope it helped clarifying it a bit.
furkan
11,733 Pointsfor (let i = 0; i < myList.length; i += 1);
/* The for loop is one of the loops you can use in javascript to run a line or multiple codes for a repeated amount of duration.
In this case, you have created a variable called i and stored the value 0 to it. You then said in your code: run the following loop for as long as the value of i (which is 0) is less than the length value of myList (which I'm guessing it is an array containing multiple values).
The array index values are where the length property comes from, so however many items you got in your array, that will be the length. So the loop will keep repeating itself and will add a 1 to the value of the variable i each time until the value of i is greater than the length value of myList array.
I hope that has made sense. If not, please refer to Mozilla developer network on Google.
All the best. */
Muhammad Khan
Courses Plus Student 8,772 Pointsfor(let i = 0; i < myList.length; i += 1) {
myList[i].style.color = `red`;
}
/* This is a for loop which is executed as long as a condition is true. the variable i is initialized to 0 as our first position of li is at 0 position because in case of array or collection the position always starts with 0. i += 1 means in every iteration 1 is added to i to get the next element till the last element (i < myList.length) */ ```