Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Array Iteration Methods Combining Array Methods Working with Objects in Arrays

Samuel Kleos
seal-mask
.a{fill-rule:evenodd;}techdegree
Samuel Kleos
Front End Web Development Techdegree Student 13,307 Points

What if... 🤔 these two methods are the same. Then is it true .reduce() is just performing a variable assignment?

const acc = {}; // this assignment is the same as.. (see next comment) 👇🏽
for (let item of users) {
    acc[item.name] = item.age;
}

const assignedAges = users.reduce((acc, item) => {
    acc[item.name] = item.age;
    return acc;
}, {}) // making the assignment here?

Therefore acc is just a constant that needs to be returned every time the multi-line callback (wrapped in braces) does a loop through each element?

1 Answer

Steven Parker
Steven Parker
231,172 Points

The optional 2nd argument to a callback is indeed assigned to the accumulator before the callback is used.

The main difference between these two examples is that "acc" in the first case is a constant but in the second case it is a function parameter.

Samuel Kleos
seal-mask
.a{fill-rule:evenodd;}techdegree
Samuel Kleos
Front End Web Development Techdegree Student 13,307 Points

So effectively, acc in the second example is first declared as a variable in the parameter of the callback, and then assigned a value in the second parameter of the .reduce() method?

Steven Parker
Steven Parker
231,172 Points

Essentially, but normally the word "variable" is not used to refer to a parameter. It would be more common to just say that it is "declared as a parameter of the callback".