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 trialAmaresh Dey
4,859 PointsNeed explanation about loop in javascript
var scores = [2,2,2,2];
var addScore = 0;
function print(message){ document.write(message); }
for (var i = 0; i<scores.length; i+=1){ addScore += scores[i]; }
var average = addScore / scores.length;
print(average);
Please need explanation what is "scores[i]" is doing in this for loop?
1 Answer
Erik Nuber
20,629 PointsTo access an array.
scores = [2, 3, 4, 5]
You can use scores[0] to access the first location holding the number 2.
scores[1] to access the first location holding the number 3
scores[2] to access the first location holding the number 4
scores[3] to access the first location holding the number 5
so in the loop, you are saying from variable i as long as it is less than the length of the array you are going to go thru it all
first time thru i = 0 so you have scores[0] and it is accessing the first location of the array
you are also increasing i by one so next time thru i=1 so you have socres[1] accessing the second locaiton of the array and so on.
edit: also, you are taking addScore which was set to 0 and each time thru the loop you are adding in the value found at that given location. When your loop is done, addScore will include everything in the array added together.
That gives you a total of 8 which you then average by dividing by the length of the array which is 4 so you get 2 and print that to the screen.
Amaresh Dey
4,859 PointsAmaresh Dey
4,859 PointsThanks.