Skip to content
Advertisement

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

Advertisement

Answer

Assuming the students array is in the format below (after you collected the inputs):

let students = [
  { name: "aaaa" , gender: "male"  , age: 17, grade: 63 },
  { name: "bbbb" , gender: "male"  , age: 20, grade: 70 },
  { name: "yyyy" , gender: "female", age: 18, grade: 45 },
  { name: "zzzz" , gender: "female", age: 18, grade: 70 },
  { name: "xxxx" , gender: "male"  , age: 20, grade: 83 },
];

One possible solution is the following:

let students = [
  { name: "aaaa" , gender: "male"  , age: 17, grade: 63 },
  { name: "bbbb" , gender: "male"  , age: 20, grade: 70 },
  { name: "yyyy" , gender: "female", age: 18, grade: 45 },
  { name: "zzzz" , gender: "female", age: 18, grade: 70 },
  { name: "xxxx" , gender: "male"  , age: 20, grade: 83 },
];
//------------------------------
function average_age(students){
let total = 0;
students.forEach(s => total +=s.age);
return total/students.length
}
//------------------------------
console.log("Average age is : " + average_age(students));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement