Codecademy Forums

FAQ: Iterators - The .reduce() Method

This community-built FAQ covers the “The .reduce() Method” exercise from the lesson “Iterators”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise The .reduce() Method

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Not unless we consider the dictionary meaning of the words, and no they are not built into JavaScript.

Parameters are locally defined variables (in function scope). We declare them arbitrarily, but in keeping with common sense use terms that describe what the variable references, or its purpose.

(accumulator, currentValue) => accumulator + currentValue

The above callback is kept going until the object array is reduced to a single value. The array itself is unchanged. Put in simple terms,

Array.reduce((a, b) => a + b))

In a sense we can think of a as being the first term in the array, and b as the last. The last term is popped off the array and added to the first term, and the new value replaces the first term. This process is repeated until there is only one term, which is the resulting value of the method.

The heavy lifting is done by the reduce method, which has a built-in iterator for stepping through the array object.

Consider this mockup of the possible code behind the method…

function reduce(array) {
  var clone = array.slice();  // a copy so the original is untouched
  while (clone.length > 1) {
    clone[0] += clone.pop();
  }
  return clone[0]
}
array = [1,1,2,3,5,8,13,21,34,55]
console.log(reduce(array))    // 143
4 Likes

Does the first chart of results miss the first iteration? Shouldn’t row 1 be:
Iteration accumulator current val return val
first 1 1

Study the array, then fill in the blanks in the table. Compute the sum and store in column 4.

[1, 2, 4, 10]

We first load the accumulator with the leftmost element of the array (index 0).

First    1

The currentValue is the next element in the array (index 1) which gives,

First    1    2

Now we compute the sum and return it. This becomes the accumulator in the second iteration. The index pointer is incremented and the process repeated.

First    1    2    3

If we were to use the algo posted earlier, the table would look like,

First      1    10    11
second    11     4    15
Third     15     2    17

since we load the currentValue with the rightmost element in the array.

2 Likes

What would be a real world example for using this method. I understand what its doing but it I guess i’m trying to picture what I’d use it for.

For a lot of these excessive I like to think about how i can apply to a real world application

Explanation of javascript’s reduce() with a real world use case

As we see, this method is not just for numeric computation.

This will seem a silly way to compute factorial…

[1,2,3,4,5,6,7].reduce((a, b) => a * b)    // 5040

but it is short and sweet. And this would seem a strange way to join strings…

array = ['A', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'];
array.reduce((a, b) => a + ' ' + b)
// "A quick brown fox jumps over the lazy dog"

Neither is very real world when compared with the example given in the article. Perhaps in your reading you will find some other examples. Please do share!

Okay, as this is a solution to the exercise, I’m going to spoiler blur it.

I get what the reduce() method (method is right, right?) is doing. But, why is the function executing without being called?

I.E. the console logs are happening without me having to call newSum();
I don’t even have to ask for newSum to be console logged. #dahell? lol!

const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
 
  console.log('The value of accumulator: ', accumulator);
console.log('The value of currentValue: ', currentValue);
  return (accumulator + currentValue);
  
}, 10 // Second argument of reduce, sets accumulator to start at 10.);

Looks like you discovered some weirdness with the error handling of JS. This code (as shown) should not run. Are we missing some of the code?

One expects you will remove the debugging logs after this.

it is being called. are you sure you know what reduce does? be careful with assumptions so that you don’t rule out answers

Your function is just ADD, same as the + operator. Some other language might write the same thing like this instead:

(reduce + [1 3 5 7])

or

reduce (+) [1, 3, 5, 7]

or

reduce(add,  [1, 3, 5, 7])

It’s a bit easier to see what’s going on without all the boilerplate you’ve got in there.

javascript doesn’t necessarily have to be worse than the above examples:

let add = (a, b) => a + b

[1, 3, 5, 7].reduce(add)

I got this exercise but only becuase the pattern is exactly the same as all the iteratir ones that came before it. I have no idea what’s happening, why it’s happening, how it’s working.

const newNumbers = [1, 3, 5, 7];
const newSum = newNumbers.reduce((accumulator, currentValue) => {
console.log('The value of accumulator: ', accumulator);
console.log('The value of currentValue: ', currentValue);
return accumulator + currentValue;
});
console.log(newSum);

1 Like

I like the way that when you click the ‘Get Help’ button, the only option is to restart the exercise, which is not much help when you need help.

It works because the method keeps a running total (the accumulator) as it iterates over the array, one value at a time.

total = 0
for (x of newNumbers) {
    total += x;
}
return total

Think of it like this…

Array.reduce((total, x) => total + x)

The second value is the iterator variable, the first is the running total.

We can if we wish write a separate function and use it as a callback for reduce

const plus = (s, x) => s + x;
array =  [2, 3, 5, 7, 11, 13, 17, 19]
array.reduce(plus)
// 77
1 Like

I’m just getting error codes after completing the assignment.

The value of the accumulator: 1
The value of currentValue:  3
The value of the accumulator: 4
The value of currentValue:  5
The value of the accumulator: 9
The value of currentValue:  7
/home/ccuser/workspace/javascript-iterators-reduce/main.js:12
console.log(newSum.reduce(newNumbers));
                   ^

TypeError: newSum.reduce is not a function
    at Object.<anonymous> (/home/ccuser/workspace/javascript-iterators-reduce/main.js:12:20)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3

and here’s the code

const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce(
  (accumulator, currentValue) => {
  
    console.log('The value of the accumulator:', accumulator);
    console.log('The value of currentValue: ', currentValue);
    
    return accumulator + currentValue;
} );

console.log(newSum.reduce(newNumbers));


As the error message states, newSum.reduce is not a function. What that means is that a number does not have a an attribute, reduce, only list object have that method. Try,

console.log(newSum)

Do I have to use accumulator as the first variable? i.e,

Does

const newSum = newNumbers.reduce((x, y) => {
  console.log('The value of x: ', x);
  console.log('The value of y: ', y);
  return x + y;
}, 10);

work as well?

No, we can use any variable we like, as you will have seen from the above.

 Array.reduce((a, b)) => a + b)
1 Like

For step one (and only step one, not moving on) I write:

const newSum = newNumbers.reduce( => {
  
});

But this is incorrect. What please is correct line of code for step one?

The function lacks the required two formal parameters:

(a, b) => {
    return a + b;
}

Thank you! That was a great explanation and now I feel like I actually understand what’s going on in the example they used for teaching the reduce() method.

1 Like
const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue;
}, 10);

console.log(newSum);

I do not understand how the arguments are being handled. Why, without an argument after the function, does accumulator take the first element of the array for value while currentValue waits for the iteration, but when adding an argument after the function then suddenly accumulator takes the value of that argument while currentValue takes the first element of the array straight away?

There must be a logic behind this, but I don’t get it. Would appreciate if someone could help me understand or direct me to a resource that explains this behavior in more details.