Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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());

about 4 years ago · Juan Pablo Isaza Denunciar

0

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));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda