Functional Programming in JS

Created by Ranjith Nair

What is FP?

  • Programming Paradigm
  • Declarative in nature rather than imperative.
  • Application state flows through pure functions.
  • Change in mindset to approach a problem.

Programming Paradigms in JS

Programming Paradigms in JS

  • Imperative JS
  • Object Oriented JS
  • Functional JS

Imperative JS

						
'use strict';

function imperativeSquare(arr) {
  /* You have to specify the followings :
      1. How to loop throgh the array
      2. The order of looping
      3. Logic
  */
  for (var i = 0; i < arr.length; i++) {
  	arr[i] *= arr[i];
  }
  return arr;
}

var a = [1, 2, 3, 4, 5];
console.log(imperativeSquare(a)); // [1, 4, 9, 16, 25]
						
					

Object Oriented JS

See the Pen YVWmdo by Ranjith (@ranjithnair) on CodePen.

Functional JS

						
'use strict';

function declarativeSquare(arr) {
	/* You have to specify the followings :
    	1. Logic
  	*/
	return arr.map((val) => val*val);
}

var a = [1, 2, 3, 4, 5];
console.log(declarativeSquare(a)); // [1, 4, 9, 16, 25]
						
					

Principles of FP

  • Side Effects
  • Pure Functions
  • Functional Composition
  • Immutability
  • Closure
  • Recursion

No Side effects

  • Function should produce same output at any point of time given same input.
  • Easier to test.
  • Side effects can cause bugs which are difficult to identify.

No Side effects

						
// A function with a side effect
var x = 10;

const myFunc = function ( y ) {
x = x + y;
};

myFunc( 3 );
console.log( x ); // 13

myFunc( 3 );
console.log( x ); // 16
						
					

Write Pure Functions

						
// Make the global variable local.
const myFunc = function ( y ) {
  const x = 10;
  return x + y;
}

console.log(myFunc( 3 )); // 13
console.log(myFunc( 3 )); // 13
						
					

Function Composition

Combine functions to form new functions

						
// The function addThenSquare is made by combining the functions add and square.
const add = function ( x, y ) {
  return x + y;
};

const square = function ( x ) {
  return x * x;
};

const addThenSquare = function ( x, y ) {
  return square(add( x, y ));
};
						
					

Currying

  • Spice up your Javascript code 🌶️ 🌶️.
  • Function doesnt take all of its arguments upfront.
  • Function returns another function and so on and each of them is invoked by seperate params.
  • Partially calling a function with few arguments which returns another function.

Currying

See the Pen Currying by Ranjith (@ranjithnair) on CodePen.

Currying in React

						
render() {
  return (
    {renderIf(1 + 2 === 3)(
      This works!
    )}
  );
}
const renderIf = predicate => element => predicate && element;
						
					

Immutability

  • Immutable --> If an object is immutable, its value cannot be modified after creation.
  • If an object is mutable, its value can be modified after creation.
  • Immutability exist by design in JS - strings & number literals
  • However, Objects & Arrays are mutable by design.
  • Whenever you want to make any change, return a new instance of that
  • Similar to "Save As" :)

Why Immutability?

  • Mutation is a side effect.
  • Stricter control over data
  • Able to do undo/redo operations easily
  • Time travel debugging
  • Better performance in React (compare before & after - only rerender when needed)

Immutability Examples

See the Pen Immutability by Ranjith (@ranjithnair) on CodePen.

Immutable Data Structure - Performance

Immutable Data Structure - Performance

DAG - Structural Sharing

Immutable Data Structure - Performance

Array & Objects: HAT-Trie

Iterating in FP

  • map
  • reduce
  • filter

map, Reduce & Filter

map, Reduce & Filter

map, Reduce & Filter

See the Pen Map, Reduce & Filter by Ranjith (@ranjithnair) on CodePen.