Functional programming in JavaScript is easy.
Easier, in fact, than OOP in JavaScript.
If you've been looking at academic discourses about functional programming with terms such as referential transparency, lambda calculus, and the dreaded monad, then it's no wonder you're confused. But you don't need to understand any of that terminology (or even the theory) to FP.
Here we present the fundamental techniques for functional programming without all the painful academic theory and terminology. You, too, can FP.
How to FP
- Functions are the basic unit of reusability
- Given the same arguments, a function must return the same result
- Functions take at least one parameter
- Functions return exactly one result
- Functions can be passed as arguments to other functions
- Functions can be returned from other functions
- Functions can call functions, including themselves
- Don't be reaching outside the function to mess with shit
- Make copies when passing by reference
- Functions can remember things for you
- Variables are “set and forget”
- Loops are so last millennium!
- Functions can call themselves! No, really!
- Use
map
to modify each value in a list - Use
reduce
to combine elements in a list - More fun with
reduce
- Use
filter
to choose particular values from a list - Use
adjust
to update a single value in a list - Use
append
,insert
, orprepend
to add an item to a list - Use
remove
to remove an item from a list - Use
concat
orzip
to combine two lists - Use
times
to create a new list - Use
head
andtail
to destructure a list - Use
all
,any
, ornone
to test a list - Use
flatten
to flatten nested lists into a single list - Avoid
forEach
! AvoidforEach
! AvoidforEach
!
- We can has pipelines!