const reduce = (reducer, initial, arr) => { // shared stuff let acc = initial; for (let i = 0, length = arr.length; i < length; i++) {
Higher Order Functions (Composing Software)
Eric Elliott
99911

Eric Elliott, thanks for the great post!
I’m learning functional programming. And it’s really a fascinating world. And we all have heard many times that mutation, i.e. reassigning different values to the same variable is a bad thing, in general. And it’s bad for several reasons. In your function reduce you’ve mutated your variable acc:

const reduce = (reducer, initial, arr) => {
// shared stuff
let acc = initial;
for (let i = 0, length = arr.length; i < length; i++) {
// unique stuff in reducer() call
acc = reducer(acc, arr[i]);
// more shared stuff
}
return acc;
};
reduce((acc, curr) => acc + curr, 0, [1,2,3]); // 6

So, what if we simplify your function even more and get rid of the assignments inside of the function and also maybe even for loop. We’ll end up with something like this:

const broReduce = (reducer, initial, arr, index) => {
if (!arr[index]) {
return initial;
}

return broReduce(reducer, reducer(initial, arr[index]), arr, index + 1);
}
broReduce((acc, curr) => acc + curr, 0, [1,2,3], 0); // 6

Here’s a couple of questions.

Is mutation really that dangerous as some Haskell and pure functional guys say? Because obviously we need to have mutation in our apps. Otherwise, software we build is not going to be much useful for a user.

And the other question:
Now we have this somewhat clean small higher order function that I’ve just written. But it became sort of cryptic and maybe even more difficult to read, even though we have fewer lines. So, in case of a big team (and I mean a really big team), do you think this kind of style of writing code — which technically make your code cleaner and more robust — will actually benefit the team? because it might actually do the opposite. It can create extra obstacles for being more productive, because it might be harder to maintain this code, since maybe many developers on that team aren’t really comfortable with writing JS in a functional way. And when it’s a small team of — let’s say— 5 people and they are at the same office, they can have a knowledge sharing session, and all that good stuff. But let’s say we have a team of 50 developers and they are in different countries and maybe very different time zones. How they can actually make a transition towards more functional approach. Especially, when you are a mid developer with maybe just 1-2 years of coding under your belt. How can you actually influence your team when you have guys with like 5–10 years of work experience, who probably know much more than you do. But they are just more object oriented guys?