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 trialolu adesina
23,007 Pointsim trying to get an average from an array where am i going wrong?
age = [30, 23, 34, 32]
averageAge = 0
function getAverageAge(x, y) {
for (i = 0; i < x.length; i += 1) {
x[i] += y
}
return y / x.length
}
getAverageAge(age, averageAge)
2 Answers
Sahil Kapoor
8,932 Pointsx[i] += y;
x[i] = x[i] + y;
// The above Two lines of code are equivalent and they means you are adding y in every element of x array any y is zero
// The correct way is
y += x[i];
y = y + x[i];
// The above two lines of code are equivalent and the means that you are adding every element of x array in y variable
martinjones1
Front End Web Development Techdegree Graduate 44,819 PointsI updated your JS to that below which seems to work OK, I would use console.log as often as possible to help debug your scripts and see if things are working as expected:
var age = [30, 23, 34, 32];
var averageAge = 0;
function getAverageAge(x, y) {
for (var i = 0; i < x.length; i++) {
averageAge += x[i];
}
averageAge /= x.length;
console.log(averageAge); // can use return averageAge instead
}
getAverageAge(age, averageAge);
olu adesina
23,007 Pointsolu adesina
23,007 Pointsthanks for this but just want ask why it matters the order
Sahil Kapoor
8,932 PointsSahil Kapoor
8,932 PointsThe interpreter computes the expression on the right side of equal "=" and then store it in the variable on the left side left side. That's why order matters in every programming language.