Functional programming in Javascript: The basics

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.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let myVar = 'Hello'

function pureReverseString(s) {
return s.split('').reverse().join('')
}

function unPureReverseString(s) {
myVar = s.split('').reverse().join('')
return myVar
}

const rev1 = pureReverseString(myVar)
console.log(myVar, rev1) // Outputs 'Hello' 'olleH'
const rev11 = pureReverseString(myVar)
console.log(myVar, rev11) // Outputs 'Hello' 'olleH'

const rev2 = unPureReverseString(myVar)
console.log(myVar, rev2) // Outputs 'olleH' 'olleH'
const rev21 = unPureReverseString(myVar)
console.log(myVar, rev21) // Outputs 'Hello' '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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Let's say we have a simple add function that adds two integers
function add(x,y) {
return x + y
}

// This is the curried function
// You can call the curried function by addCurried(1)(2) to add 1+2
function addCurried(what) {
return function(num) {
return what+num
}
}

const addFive = addCurried(5) // Partial curried function
const addThree = addCurried(3) // Partial curried function

console.log(addFive(4)) // Outputs 9
console.log(addFive(4)) // Outputs 9

console.log(addThree(4)) // Outputs 7
console.log(addThree(4)) // Outputs 7

Again, not super useful example but consider a role play where addFive could be something like swordHit and addThree might be knifeHit.

I’ll continue exploring functional programming in Javascript more in depth in future posts.