Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda