DEV Community

Discussion on: Is functional programming in JS really worth it?

Collapse
 
dannymcgee profile image
Danny McGee • Edited

FP doesn't mean you're not allowed to string two tokens together unless they're functions. :P You have to compare apples to apples. Let's take an array of words, transform it into an array of numbers (where each number is the number of letters in that word), filter out the numbers that are odd, add all the numbers together.

This is imperative:

let result = 0;
for (let word of words) {
  let length = word.length;
  if (length % 2 === 0) {
    result += length;
  }
}
return result;
Enter fullscreen mode Exit fullscreen mode

This is functional:

return words
  .map(word => word.length)
  .filter(length => length % 2 === 0)
  .reduce((accum, current) => accum + current);
Enter fullscreen mode Exit fullscreen mode

Technically that's OO, since we're using methods on the Array object, but this is fundamentally an FP-style operation: it's declarative, it doesn't mutate anything, and there's no control structures. You could write the same thing with pure, free functions in a pipe instead of the method chaining. Here's what it would look like with lodash/fp:

return flow(
  map(word => word.length),
  filter(length => length % 2 === 0),
  reduce((accum, current) => accum + current)
)(words);
Enter fullscreen mode Exit fullscreen mode