DEV Community

Discussion on: Writing modern JavaScript code

Collapse
 
gmaiolo profile image
Guillermo Maiolo • Edited

You're confusing functional programming with extreme immutability, which is an anti-pattern by itself, generating an incredible amount of overhead.
You're literally advocating to loop three times instead of one just to force yourself to use map, filter and reduce.

I understand these are examples, but they're extremely bad examples for any apprentice dev so this needs to be clarified.

While the post correctly encourages having immutable data, the idea is to keep that data updated with pure functions. Now, pure functions must avoid shared state, mutable data, and side-effects outside of their bounds but not necessarily inside, this simple concept may be hard to grasp at first, so let me try to show it with the examples you used:

// Instead of:
const res = arr
  .map(elem => ({ name: elem.name, calculatedValue: elem.value * 10 }))
  .filter(elem => elem.calculatedValue > 100)
  .reduce((acc, elem) => ({
    [elem.name]: calculatedValue,
    ...acc
  }), {})

// Prefer:
const res = (() => {
  let obj = {}
  for (let i = 0; i < arr.length; i++) {
    const calculatedValue = arr[i].value * 10
    if (calculatedValue > 100) {
      obj[arr[i].name] = calculatedValue
    }
  }
  return obj
})()

Of course it may or may not be better to use Object.keys().forEach() or even Object.keys().map() and still loop once doing all the needed calculations on the fly as well, but the point is that yes, pure functions and functional programming should be used, but we must always have in mind that both of them can use and abuse of mutable data correctly contained and that's not bad, it's actually one of the beauties of Javascript.

Collapse
 
tiffany profile image
tiff

Can you give a better example without chaining together map, filter, and reduce but still keeping it functional? Why is it an anti-pattern?