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
mapto modify each value in a list - Use
reduceto combine elements in a list - More fun with
reduce - Use
filterto choose particular values from a list - Use
adjustto update a single value in a list - Use
append,insert, orprependto add an item to a list - Use
removeto remove an item from a list - Use
concatorzipto combine two lists - Use
timesto create a new list - Use
headandtailto destructure a list - Use
all,any, ornoneto test a list - Use
flattento flatten nested lists into a single list - Avoid
forEach! AvoidforEach! AvoidforEach!
- We can has pipelines!