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 trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

Vic Mercier
Vic Mercier
3,276 Points

average calculator

Is someone able to do an average calculator with for loop an array?If yes show me how.

4 Answers

Vic Mercier
Vic Mercier
3,276 Points

var numbers = [1,2,3]; var total; for(var i = 0; i < numbers.length;i += 1){ total += numbers[i]; } var average = total/numbers.length; alert(average); Is it good.If not show me your solution.

Steven Parker
Steven Parker
231,275 Points

That's good except you forgot to initialize your total.

So instead of: "var total;", you might write: "var total = 0;"

Steven Parker
Steven Parker
231,275 Points

Give this a try yourself.

If you combine what you just learned about loops and arrays with what you did in JavaScript Basics, you should be able to at least give it a try.

Vic Mercier
Vic Mercier
3,276 Points

Yes I know but I finished the array loop and object and i am not able

Steven Parker
Steven Parker
231,275 Points

You might use a technique from the courses: start with breaking the project down into separate tasks, define the tasks with comments, and then fill in code for each. Here's a sample:

// construct an array with the proper contents

// create a variable to hold a total

// make a loop that will run once for each item in the array

    // inside the loop, add each item to the total

// after the loop, divide the total by the number of items and store that in a new variable

// finally, pick a way to display the average.  alert?  log?  write into the document?
Vic Mercier
Vic Mercier
3,276 Points

var numbers = [1,2,3]; var total; for(var i = 0; i < numbers.lenght; i +=1){ total += numbers[i];

} Am I well started? And I will divide the total by numbers.lenght

Steven Parker
Steven Parker
231,275 Points

You wrote "lenght" instead of "length", but otherwise it looks like you got the first 4 items there. Just two more and you'll have it functioning.

Vic Mercier
Vic Mercier
3,276 Points

Should I use a for loop?