As a completely new developer, my favorite JavaScript tools were .map() and for loops. But recently, I've been determined to understand more complex methods like .reduce.
Working through the Callbacks & Higher-order Functions challenges in CSX has been the perfect introduction to reduce, which was intimidating for me to get started with. But reduce is a powerful method and definitely worth the effort.
The first .reduce() method I was exposed to was via MDN
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
The W3Schools definition was better, but not by much.
So what's the best way to get over this intimidation factor?
1) start small with basic examples
- Most newbies are familiar with using .reduce() to aggregate the elements in an array
const theOG = (array) => {
return array.reduce((acc, el) => {
return acc + el
})
}
2) remove any confusing terminology-- accumulator? What callback?
- I played with simple reduce applications using just x and y.
- But it might make more sense for you to use total and current or total and item
- Doesn't this syntax look familiar?
return array.reduce((x, y) => x + y % 2)
return array.reduce((x, y) => x - y)
3) console.log a lot
- If you're not sure what reduce is doing, console.log and see how that matches with your expectation.
const reduces = (array) => {
return array.reduce((acc, num) => {
console.log(acc, num)
return acc + num
})
}
4) add other arguments and console.log those
array.reduce((acc, num, index, array) => {
console.log(num, index)
5) practice + repetition
- Challenge yourself to solve different problems using .reduce() instead of the more obvious loops or methods.
- Solve the same problems over and over until they become second nature
- For me, the CSX challenges did a great job of that, but you can also make up your own challenges
As with every topic, FreeCodeCamp has a straightforward article you can reference when stuck.
You can also view my reduce challenges here
Top comments (2)
These are great tips for any JavaScript array method! I love it. Great post.
Thanks!