'function returning NaN in javascript

I am trying to write a function that calculates the average student age in a list of student objects, but when I run the code the function prints NaN as an output

function average_age(){
    let total = 0;
    students.forEach(s => {
        total += Number(s.age);
    });
    return  total/size
}
console.log("Average age is : " + average_age())

this is how i constructed the array ( i got the input from the user)

const size = 5
let students = [size]

for (let i=1; i<=5; i++){
    let name = prompt("Enter student's name: ")
    let gender = prompt ("Enter student's gender: ")

    students.push({
        name: name,
        gender: gender,
        age:Math.round(Math.random() * (35 - 17 + 1) + 1),
        grade:Math.round(Math.random() * (100 + 1))
    })
}

//display student info
students.map(s =>{
    console.log("Name: " + s.name);
    console.log("gender: " + s.gender);
    console.log("age: " + s.age);
    console.log("grade: " + s.grade);
    console.log();
})

i tried to calculate the total of student age (removing the divide operation) to check if the problem was the division but i still got NaN as an output



Solution 1:[1]

You can check 3 approaches down there for your problem:

const students = [
  { id: 1, name: "john", age: 25 },
  { id: 2, name: "jack", age: 31 },
  { id: 3, name: "joe", age: 26 },
  { id: 4, name: "jamal", age: 21 },
];

// Your approach:
function average_age() {
  let total = 0;
  let numberOfStudents = students.length;
  
  students.map(student => {
    total += Number(student.age);
  });
  
  return total / numberOfStudents;
}

// Second approach:
function average_age_second() {
  let total = 0;
  let numberOfStudents = students.length;
  
  students.forEach(student => {
    total += Number(student.age);
  });
  
  return total / numberOfStudents;
}

// Third approach: 
function average_age_third() {
  let numberOfStudents = students.length;
  
  const total = students.reduce((partialSum, student) => partialSum + student.age, 0);
  
  return total / numberOfStudents;
}   

console.log("Average age is : " + average_age());
console.log("Average age is : " + average_age_second());
console.log("Average age is : " + average_age_third());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1