Thank you for your article.
Jesper Hessius
11

Thank you! ^^

TL;DR: As long as the code is more readable there is no problem in using foreach , specially when few mutations are happening, it is always better to have a code that is stupid easy to understand than to have a unnecessary abstraction just because “I want to force everything to be functional”.

The drawback of forEach is that you end up having to make mutations most of the time, consider the largerThanTwo example:

const result = []
const values = [1,2,3]
values.forEach((value) => {
if (value > 2) result.push(value)
})
console.log('---->', result)

You mutate result to add the resulting values which, it is indeed no big deal in such a small scale since only one mutation is happening, in a more complex example were various mutations happen each mutation might cost you precious debug and implementation time (specially when they come from different sources) to find out were they are made (the larger the code base the worst this becomes and it gets worse without functions being pure).

The example I give in the article for recursive is not the greatest of apples so it might seem that recursion is imperative since it has some mutations happening in the mix, I might change it later for this largerThanTwo recursion following a more functional approach:

function largerThanTwo(values, index = 0, result = []) {
const currentValue = values[index]

if (!currentValue) return result
  const newResult = currentValue > 2
? [].concat(result, currentValue)
: result

return largerThanTwo(values, (index+1), newResult)
}

It ends up like you say less readable and there is not much of a real gain just to get rid of one mutation that can easily be contained so forEach works just fine.

While my example ends up not defending recursive functions I might be able to give a glimpse of were they might shine so, if it fancies your interest, heres a small challenge:

  • Find a solution in imperative and another using recursion that will iterate and log every value of the following arrays:

[1, [2, 3]] // three console.log outputs

[1, 2, [4, 2]] // four console.log outputs

[1, [1, 2], [6, [25, [8]]], [7, 9]] // eight console.log outputs

A real scenario of a similar format to this is, for example, a website menu were you don’t know how many menus there are and how many sub levels they have (and the number of items of each sub level).

In the solutions to this I’ve seen up until now the recursive ends up making the solution possible while being readable and flexible but I’m always ready to be surprised.

Even if you don’t care for the “challenge” since you already know it or aren’t interested I do really hope I answered your question and that you keep up with your rewrite! ^^