Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!