infuerno.github.io

Frontend Masters: Functional Javascript First Steps

References

What is Functional Programming

Staying out of the Loop with Recursion

Higher Order Functions

Higher Order Function : Takes other functions as inputs and / or outputs

This is a key technique in functional programming. map, reduce, filter are all higher order functions.

Closure

When returning a function from another function, the function returned will still have access to any variables which were in scope when it was returned.

function makeAdjectifier(adjective) {
  return function (noun) {
    return adjective + " " + noun;
  };
}
const coolify = makeAdjectifier("cool");
coolify("workshop"); // "cool workshop"
coolify("drink"); // "cool drink"

Partial Application

Can therefore have functions which remember certain arguments “partially apply” to “lock in” some arguments and make more reusable functions.

Currying

Breaks up a multi argument function into a series of single arg ones. This makes it easier to reuse the smaller functions.

Function Composition

g(f(x))

This is almost the opposite of currying. Having broken down functions into smaller one argument functions, we then construct programs entirely out of modular pure functions, using function composition to “combine” several functions’ effects to create a pipeline through which our program’s data can flow.

Immutability

Avoid mutability for happier programming. However copying data is not efficient. It takes time AND space. This is a challenge for functional programming.

The solution is special types of data structures which are immutable BUT also effecient. These are known as “immutable data structures” / “persistent data structures”

Immutable Data Structures

Immutable.js and Immer are two popular libraries.

Next Steps

Anouk Ruhaak

https://www.youtube.com/watch?v=6f5dt923FmQ

State has to deal with 3 issues:

  1. Race conditions - code which checks an external flag and then does something based on the value of the external flag will work great with 1 thread, but can suffer from race conditions for more than 1 thread: IF no orange in the basket THEN get one and put it in Race Conditions
  2. Complexity - list, basket, but what about the type of supermarket, my mood for the day
  3. Unpredictability. Even a super simple function will return completely different things each time IF it depends on the value of an external variable
x = 1;
function timesTwo() {
  return x * 2;
}
console.log(timesTwo(1)); // => 2
console.log(timesTwo(2)); // => 4

Getting more relevant because today more and more code is run multi-threaded.