Javascript: Functional

functional programming refers to the declarative evaluation of pure functions to create immutable programs by avoiding externally observable side effects

Object Orientation makes code understandable by encapsulating moving parts.

Functional Programing makes code understandable by minimizing moving parts.

Fundamental Concepts

  • Declarative programming
  • Pure functions
  • Referential transparency
  • Immutability

Declarative programming

  • OOP uses imperative or procedural: sequence of top-to-bottom statements that changes the state of the system in order to compute a result

    var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; for(let i = 0; i < array.length; i++) { array[i] = Math.pow(array[i], 2); } array; //-> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

  • Declarative Programming Paradigms: expresses a set of operations without revealing how they’re implemented or how data flows through them.

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map( function(num) { return Math.pow(num, 2); }); OR [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(num => Math.pow(num, 2)); //-> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    • expressions to describe logic of a program without necessarily specifying its control flow or state changes.
    • e.g. SQL queries describe what the outcome of a query should look like, abstracting the internal mechanism for data retrieval

Pure Functions

  • Depends only on the input and not on any hidden or external state that may change during its evaluation or between calls
  • Doesn’t inflict changes beyond their scope, such as modifying a global object or a parameter passed by reference.
  • Use Curry functions to separate out Pure and Impure functions

Referential transparency or Equational correctness

Function consistently yields the same result on the same input

Preserving immutable data

e.g. Array.sort function is stateful and causes the side effect of sorting the array in place

Benefits FP brings to your JavaScript Applications

  • Encouraging the decomposition of complex tasks
  • Process data using fluent chains
  • Decrease the complexity of event-driven code by enabling reactive paradigms

Encouraging the decomposition of complex tasks

Functional programming is effectively the interplay between decomposition (breaking programs into small pieces) and composition (joining the pieces back together)

  • Should follow Single responsibility Principle
  • Purity and RReferential Transparency encourage this.
  • Then use Composition to glue simple functions togather.

Function Composition: is the process of combining two or more functions to produce a new function. Composing functions together is like snapping together a series of pipes for our data to flow through.

Processing data using fluent chains

  • A function chain is a lazy evaluated program which simulates call-by-need behavior

Reacting to the complexity of asynchronous Applications

Higher-Order Functions and Closures