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))
CodePudding user response:
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.
You have not used parenthesis, you are essentially doing
a ( b / len )
which will lead to an incorrect answerYou 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;
}
CodePudding user response:
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))