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 Writing the JavaScript Code

Can anyone tell me why my .forEach is failing?

I tried using a .forEach instead of a for loop - can anyone see what's wrong with my code?

function calculate_gpa(student_grades){
  const grade_total = 0;
  const number_of_grades = student_grades.length;
  student_grades.forEach((element) => {
    if(element < 1 || element > 4){
      console.log("Invalid grade: " + element);
      return "Can't complete calculation.";
    } else {
      grade_total += student_grades[i];
    }
  });
  const gpa = grade_total / number_of_grades;
  return gpa;
}
const reggie_grades = [4, 4, 3, 4];
const dave_grades = [1, 2, 3, 2];
console.log(calculate_gpa(reggie_grades));
console.log(calculate_gpa(dave_grades));

2 Answers

In first glance ur using a forEach loop. You can't access elements in the array with a [] when ur using forEach loop. The forEach() method calls a function once for each element in an array, in order

 grade_total += student_grades[i];

It should be:

 grade_total += element;

can u give a snapshot?