DEV Community

Discussion on: Ask me dumb questions about functional programming

Collapse
 
mohamedelidrissi profile image
Mohamed Elidrissi • Edited

Explain to me functional programming like I'm 5, you said dumb questions right? Seriously though I hear this term but I'm always lazy to search it up.

Collapse
 
joelnet profile image
JavaScript Joel • Edited

To me, functional programming is all about composing (or combining) functions to create new functions.

A good example of this would be map and it's siblings filter and reduce.

Imperative

const values = [1, 2, 3]

let sum = 0
for (const x of values) {
  sum = sum + x
}

Functional

const values = [1, 2, 3]

const add = (x, y) => x + y
let sum = values.reduce(add)

Instead of coding all the steps to create the sum, we told reduce to use the add function.

If we were using something like Ramda, we could even do this to create a new function:

import { reduce } from 'ramda'

const add = (x, y) => x + y

// Here we are composing a new function `sum` from `reduce` and `add`.
const sum = reduce (add) (0)

const values = [1, 2, 3]
sum (values) //=> 6

To be able to compose functions like this, you need to also create pure functions, curried functions and also have immutable data. Which is why functional programming can be tricky to learn. It's not difficult to learn, it just takes time to fully understand the why.

I hope this was helpful!

Cheers!

Collapse
 
jochemstoel profile image
Jochem Stoel

To me it is not just composition but also isolation.

Thread Thread
 
joelnet profile image
JavaScript Joel

There are many good things. I tried to boil it down to one for simplicity.

For me, it's also about not having the mistakes of OOP: Inheritance, State, Mutations, Combining data + functions into one Object, Access Modifiers (public, private, internal, protected), property accessors get/set. etc.

Thread Thread
 
jochemstoel profile image
Jochem Stoel

Yeah but still we need streams and emitters.

Thread Thread
 
joelnet profile image
JavaScript Joel

For sure. I use event emitters also. I usually tie those in together with RXJS.

Thread Thread
 
jochemstoel profile image
Jochem Stoel

You know, everybody is like rxjs and mocha and Jasmine and mojiscript and asynchronous curry ketchup frameworks but to me they are just collections of 'helpers' from other people that I like to write myself most of the time. Functional programming to me is closely related to context free development and that means elimiting dependencies. If functional programming really insists on being a thing then don't clean up only the language but also the rest.

Collapse
 
mohamedelidrissi profile image
Mohamed Elidrissi

Now that's something a 5 years old can understand lol. Thanks!

Thread Thread
 
joelnet profile image
JavaScript Joel

Happy that you were satisfied with the answer. Hopefully others can also chime in with what functional programming means to them.

And don't be shy about asking more questions ;)