Functional Programming Basics

Pure functions

What makes a function a pure one is that it takes all the data from it's input parameters, has no side effects, and always returns the same output given the same input.

Note: If you add something to local storage inside your function, or print to screen etc. it is impure

Immutable types

The only way to change data, is by storing the change in a new variable.

Note: only use const

Function Composition

You can take multiple functions and compose them.

Currying / Partial applicativity

Allows you to pass parameters to a function in different calls, and once all parameters are supplied, the actual function is called.

Higher Order Functions

A function that either takes a function as input or produces a function as output or both.

Why Functional JS

  • Fewer bugs
  • More testable (same input same output)
  • Smaller units (in functional if you want a banana you get the banana, whereas in object oriented you also get the gorilla and the jungle with it)

Functional React

  • Unidirectional Data Flow (kind of enforces immutability)
  • Functional Components (allows to return JSX from a function)
  • Redux is a functional state management
  • Immutablejs
  • TypeScript

Shortcomings

  • Class Mutations: you can use classes instead of functions, and you can mutate their state etc.
  • Lifecycle and animations: in ReactNative you can only do animations if you use a class component
    • Some libraries work around that
  • Data transform, you are allowed to use for loops inside render method

Cool libs

  • Ramda npm i ramda, npm i -D types/ramda
  • Recompose: gives you a lot of HOC which allow you to wrap you functions with things for which you would usually need a class for
  • (react functional lifecycle)