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

206
Vistas
My Javascript AVG Calculator doesn't work. How can i fix?

I wanted to create a function that calculate the average between some numbers. I wanted to make it that i could put as many numbers as i wanted in the console.log but this code apparently doesn't work, when i console.log it says "infinity". Need help please

function avg(...args){
      return args.reduce(function (a, b) {
        return a + b / avg.length
      })
    }
    console.log(avg(1, 2, 3, 4, 5))
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use reduce and arguments length like this. You had some mistakes in your code.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

console.log(average(1,2,3,4))

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is because the variable avg does not exist, and it will default to 0. Causing it to be Infinity.

You also have 2 additional mistakes.

  1. You have not used parenthesis, you are essentially doing a + ( b / len ) which will lead to an incorrect answer

  2. You are using incorrect formula for average, in the implementation that you are using, you should be using the running average formula : refer here : How to calculate moving average without keeping the count and data-total?

this would be the correct solution :

    function avg(...args) {
        const sum = args.reduce((a,b) => a + b , 0 );
        return sum / args.length;
    }
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