This post will be an intro to the very basics of functional programming style. Before I begin, let’s defins what I mean by
Functional programming is a paradigm, style, just like object oriented programming is.
There are two differences you must understand if you’re coming from a OO background.
Composition over inheritance: In functional programming there’s no inheritance. Objects and functions are composed to become what you want.
Functions must be pure / have no side effects: A function should never mutate / change the value of anything outside it’s own scope. It must always leave it untouced so that calling the function has no side effects in our app and we should always expect the same result if we call it multiple times.
let myVar = 'Hello'
Quite silly example, but we clearly see that the second function mutates the
myVar variable which could have side effects on our app. And also, when calling it multiple times with the same input variable we get different results.
Hard to test and debug.
This is the basics.
Functional programming also uses something called curried functions or just currying. This is a quite cool and handy way of composing functions that can be used later over and over again.
// Let's say we have a simple add function that adds two integers
Again, not super useful example but consider a role play where
addFive could be something like
addThree might be