Stefano Saitta Stefano Saitta - 4 years ago 103
Javascript Question

What is the meaning of check for this.length into a function?

I'm following an online course about Javascript Functional Programming
at the Exercise 16 it show you how reduce is actually implemented, in order to help you understand how to use it, but into this implementation there is something i don't actually get, i'll show the code:

Array.prototype.reduce = function(combiner, initialValue) {
var counter, accumulatedValue;

// If the array is empty, do nothing
if (this.length === 0) {
return this;
else {
// If the user didn't pass an initial value, use the first item.
if (arguments.length === 1) {
counter = 1;
accumulatedValue = this[0];
else if (arguments.length >= 2) {
counter = 0;
accumulatedValue = initialValue;
else {
throw "Invalid arguments.";

// Loop through the array, feeding the current value and the result of
// the previous computation back into the combiner function until
// we've exhausted the entire array and are left with only one value.
while(counter < this.length) {
accumulatedValue = combiner(accumulatedValue, this[counter])

return [accumulatedValue];

I don't understand the first if statement, when it check for
what this actually mean?

Take note this is different from the reduce in ES5, which returns an value instead of an Array, this is used just as a sample for the learning purpose.

Answer Source
Array.prototype.reduce = function(...

is saying, "create a function on the prototype of Array" - this means that the new reduce function will be callable on all arrays, eg:

[1, 2, 3].reduce(...

This means you can also call it on empty arrays, eg:


Building on the comment:

If the array is empty, do nothing

You're working on an array, and when the function is called, this is set to the array that reduce was called on. This implementation of reduce assumes that if that array is empty (ie this.length === 0), you can't logically reduce it any further - there's nothing to reduce, so you can return the same empty array.

As pointed out by @Alnitak in the comments, this implementation of reduce is flawed as compared to the specification. A different implementation is available on the MDN for polyfilling older browsers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download