While working with arrays in JavaScript, Here I tried to calculate average using reduce method.
My question is at line 3: without using bracket avg + num/ arr.length
gives correct output but using bracket (avg + num) / arr.length
gives wrong output.
Can anyone explain what’s the reason behind this wired behavior?
const calcAverage = function (nums) {
const average = nums.reduce(
(avg, num, i, arr) => (avg + num) / arr.length,
0
);
return average;
};
const avg = calcAverage([1, 1, 1, 1, 1]);
console.log(avg);