FP / Functional programming in JavaScript

FP in JavaScript

Functional programming

Sergej Chodarev

JavaScript

The World's Most Misunderstood Programming Language

History

Functions as values

var add = function(x, y) { return x + y };

Higher-order functions

[1, 4, 9, 16].map((x) => x * 2)
words.filter((word) => word.length > 6)
numbers.reduce((acc, x) => acc + x, 0)

Composition

const compose = (a, b) => (c) => a(b(c));

Function application

Function context

let dog = {
    name: 'Sparky'
    breed: 'mutt'
}
dog.bark = function() {
    console.log(this.name + ": woof!");
}

dog.bark(); // logs "Sparky: woof!"

call()

call(thisArg, arg1, arg2, /* …, */ argN)
function bark() {
    console.log(this.name + ": woof!");
}

bark.call(dog);

apply()

apply(thisArg, argsArray);
const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);

console.log(max);  // 7

bind()

bind(thisArg)
bind(thisArg, arg1, arg2, /* …, */ argN)
const module = {
  x: 42,
  getX: function () {
    return this.x;
  },
};
const unboundGetX = module.getX;
console.log(unboundGetX());  // output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());  // output: 42

Partial application

const add5 = add.bind(null, 5);
add5(10);  // 15

Libraries

Closures

function init() {
  const name = "Mozilla";
  function displayName() {
    console.log(name);
  }
  displayName();
}
init();
function makeFunc() {
  const name = "Mozilla";
  function displayName() {
    console.log(name);
  }
  return displayName;
}

const myFunc = makeFunc();
myFunc();

Private methods

const makeCounter = function () {
  let privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment() { changeBy(1); },
    decrement() { changeBy(-1); },
    value() { return privateCounter; },
  };
};
const counter1 = makeCounter();
const counter2 = makeCounter();

console.log(counter1.value()); // 0

counter1.increment();
counter1.increment();
console.log(counter1.value()); // 2
console.log(counter2.value()); // 0

I Promise!

Callbacks

fetchData((data) => {
    processData(data, (processedData) => {
        saveData(processedData, (finalData) => {
            console.log("Final Result:", finalData);
        });
    });
});

Promise

fetchData()
    .then(processData)
    .then(saveData)
    .then((finalData) => {
        console.log("Final Result:", finalData);
    });

Something similar?

>>=

Is Promise a Monad?

Almost

async/await

async function main() {
    const data = await fetchData();
    const processedData = await processData(data);
    const finalData = await saveData(processedData);
    console.log("Final Result:", finalData);
}

Similar again?

async/await is just the do-notation of the Promise monad

Functional Reactive Programming

Excel

RxJS

let count = 0;
const rate = 1000;
let lastClick = Date.now() - rate;
document.addEventListener('click', (event) => {
  if (Date.now() - lastClick >= rate) {
    count += event.clientX;
    console.log(count);
    lastClick = Date.now();
  }
});
import { fromEvent, throttleTime, map, scan } from 'rxjs';

fromEvent(document, 'click')
  .pipe(
    throttleTime(1000),
    map((event) => event.clientX),
    scan((count, clientX) => count + clientX, 0)
  )
  .subscribe((count) => console.log(count));

Observables are Monads

What about React?

React