Understanding How Array Averaging Works – JavaScript – SitePoint Forums

0
const arr = [1, 2, 3, 4, 5];

var sum = 0;
for (var number of arr) {
    sum += number;
}
average = sum / arr.length;
console.log(average);

Hi all, I have a few questions about how this piece of JavaScript works. I understand what he’s doing, but I still have a few questions.

  1. The use of var. I understand that it is no longer recommended to use var and yet this code starts with constant? Is this an oversight or is there a reason it was written this way?
  2. On the topic of variable declaration, why isn’t the average preceded by constant Where let?
  3. Finally how exactly of interact with the variable Number and the table?


As you’ve already noticed, it’s usually best to stay consistent with using const and var. I would like to either rename const to var or update the code to use const and other techniques such as array reduction to good effect.

I can come back in a few hours with proper details.



1 like

As for using const, I find it efficient to replace all vars with const and fix all the issues from there. I will also use const with the mean, as this is currently defined as a global variable best avoided.

Sum and for loop cannot be used with const, because reassignment of sum occurs, so let is used instead.

const arr = [1, 2, 3, 4, 5];

let sum = 0;
for (let number of arr) {
    sum += number;
}
const average = sum / arr.length;
console.log(average);

It’s best not to use let, as reassignment tends to cause problems. Luckily, we have array methods like map, filter, and reduce to help you with these tasks.

In this case, the reduce method will benefit us here.

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce(function (total, number) {
    return total + number;
});
const average = sum / arr.length;
console.log(average);

And if more modern techniques such as arrow notation are used, it might look like this:

const arr = [1, 2, 3, 4, 5];
const sum = (total, number) => total + number;
const average = arr.reduce(sum) / arr.length;
console.log(average);



1 like

Share.

Comments are closed.