DEV Community

Discussion on: An introduction to the basic principles of Functional Programming

Collapse
 
somedood profile image
Basti Ortiz • Edited

To me, the best part of functional programming in the context of JavaScript is the ability to chain function calls. Immutability forces the implementation of functions to strictly return something given an input without any side effects. It is much more readable to see a chain of array methods rather than a bunch of for loops (bonus points if nested).

const someNums = [-1, -2, -3, 4, 5];

// This function returns the sum
// of the squares of the positive numbers
// in an array.
function getSum(nums) {
  return nums
    .filter(x => (x > 0))
    .map(x => x ** 2)
    .reduce((prev, curr) => (prev + curr));
}

console.log(getSum(someNums)); // 41
Collapse
 
teekay profile image
TK

Exactly!

Pure functions + immutability helps a lot to compose functions (or in your words "chain function calls"). And software is all about solving small parts and compose all "solutions" to solve the complex problem (bigger problem).

I will definitely write a separate post about composition!

Collapse
 
somedood profile image
Basti Ortiz

Looking forward to it! I'd love to see the different ways to compose functions.