Understanding How Array Averaging Works – JavaScript – SitePoint Forums

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);



2 likes

It’s a good idea to provide an initial value with reduce. If you try it with an empty array, an error will occur.

Uncaught TypeError: Reduce of empty array with no initial value

to fix

const average = arr.reduce(sum, 0) / arr.length;



1 like

Thanks, I tend to rely on the default behavior of reduce where without an initial value it uses the first element of the array instead.



1 like

I always have trouble with this “optimization”.
In my eyes this is not consistent with the function itself but a weird special behavior just to help reduce the typing of a few characters.

I always have trouble with this “optimization”.

What are you talking about @Thallius specifically. reduce vs for loop? reduce(function(total, count)…)) vs reduce(sum)? or dropping the zero?

Sorry until most of the night so a bit sketchy

No, I mean, this “magic” that reduces uses the first element of an array if there is no given starting value.
In my understanding of Paul’s example

const sum = (total, number) => total + number;
const average = arr.reduce(sum) / arr.length;

I should get a “number is not defined” error.



1 like

In fact, you should expect to get NaN. (Javascript doesn’t mind appending numbers to Undefined, it just returns NaN accordingly)

What actually happens is defined by the JavaScript definition of the reduce function.

If the initial value of the accumulator is not specified (it would be a parameter after the function definition), the loop does not start at index 0; it instead starts at index 1 and uses the value of index 0 as the initial value of the accumulator. (That’s why it throws an error if the array is empty, because there is no 0th or 1st array element to use)



1 like

I know, and that’s what I mean by “magic” “optimization”. I don’t like these “hidden features” which are not simple but only implemented because they shorten the code by a few characters.

Maybe. But it was probably also implemented because of that quirk above of adding numbers to Undefined not being an error in Javascript.

@ThailiusI haven’t checked scala, haskel or lisp yet, but this seems to be a standard implementation of reduce/fold, rather than just a javascript quirk.

php array_reduce

initial

If the option initial is available, it will be used at the start of the process, or as the final result if the array is empty.

python reduction (according to the docs)

Roughly equivalent to:

def reduce(function, iterable, initializer=None):
   it = iter(iterable)
   if initializer is None:
       value = next(it)
   else:
       value = initializer
   for element in it:
       value = function(value, element)
   return value

James S. Joseph