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