f(s(a)); Functional Programming in JavaScript
...which is what, exactly? Functional programming is a programming paradigm that emphasizes: Immutable data over mutable data Pure functions over functions with side effects Expressions over statements
Traditional imperative/object-oriented programming uses... Mutable state/variables For loops over recursion Functions with side effects
But...What if I told you... You don't need for loops and mutable variables
In order to avoid mutable variables, for loops, etc., functional programmers emphasize a few key concepts
Pure functions No side effects Referential transparency - if it is called with the same arguments, it will always output the same value No data dependency between pure functions - order and parellelization will not effect how the function runs
Recursion Can be used in place of traditional looping Traditional application for a loop: summing a range function sumRange(start, end) { var total = 0; for (var i = start; i <= end; i++) total += i; return total; } sumRange(1, 10); // returns 55
Now, with recursion... function sumRange(start, end, acc) { return start > end? acc: sumRange(start + 1, end, acc + start); } sumRange(1, 10, 0); // also returns 55, but cooler
But wait, recursion is slow! Not necessarily!
Tail Call Optimization Implemented as of ES2015 ("ES6") ES2015 compilers can optimize tail recursive functions in strict mode What is a tail recursive function? A function whose main recursive call is in tail position (i.e., the recursive call is the last call in the function)
Higher order/ rst-class functions
But rst, a little history... In the 1930's, mathmatician Alonzo Church invented Ξ» ("lambda") calculus, a model of computation based on function abstraction, variable binding and substitution This gave programmers a useful tool called the Ξ» function AKA the "anonymous function"
In JavaScript, Ξ» functions are possible because functions are rst-class objects. They can be: Stored in variables Passed to functions Returned from functions This allows us to use a very cool functional programming technique called...
Currying
Currying is a functional programming technique that allows us to transform a function of arity (the number of arguments a function takes) N into a chain of N functions of arity 1 A currying function allows us to partially apply functions in a very useful, exible way: function sumThree(a, b, c) { return a + b + c; } var curriedSumThree = curry(sumThree); curriedSumThree(1)(2)(3); // 6 curriedSumThree(1,2)(3); // 6 curriedSumThree(1,2,3); // 6 curriedSumThree(1)(2,3); // 6
...how? ES2015 makes writing a curry function pretty straightfoward using arrow functions and the rest/spread syntax function curry(fn) { return function curried(...args) { return args.length >= fn.length ? fn.call(this, ...args) : (...rest) => { return curried.call(this, ...args, ...rest); }; }; } Source: http://www.datchley.name/currying-vs-partial-application/
Ok...but why? It's cool DRY - Tiny, little, exible, reusable functions Because, with currying, we can very easily perform...
Function composition Composition allows us to put together functions in a compact, readible syntax that accurately re ects what we are trying to do with our code const add = (x, y) => x + y; const mult = (x, y) => x * y; const curriedAdd = curry(add); const curriedMult = curry(mult); const add2 = curriedAdd(2); const mult3 = curriedMult(3); const add2AfterMult3 = compose(add2, mult3); add2AfterMult3(4); // returns 14
The compose function Recursion + the rest/spread syntax allows us to express this very concisely const compose = (f, ...rest) => !rest.length? f: (...args) => f(compose(...rest)(...args));
Limitations JavaScript is not a purely functional language. Among other things, it lacks: True immutability: even 'const' does not truly prevent you from mutating data, e.g.: Built-in function composition Automatically curried functions const user = {name: "johnson", number: 85}; user.name = "ochocinco"; // no error!
Some functional JS libraries lodash.js, underscore.js, lazy.js, ramda.js: Utility libraries that provide FP functionality, including composition and currying, as well as the usual suspects(map, reduce, lter, etc.). Lodash and Lazy.js are particularly interesting for their use of lazy evaluation, a concept associated with FP, to optimize performance immutable.js - Provides immutable data structures
Purely functional languages These provide enhanced functional programming features/performance, and often force you into a functional programming style Haskell Elm There are also many "impure" functional languages that are still "more" functional than JavaScript, including: Scala Clojure Lisp Erlang
Happy hacking!

Functional Programming in JavaScript

  • 1.
  • 2.
    ...which is what,exactly? Functional programming is a programming paradigm that emphasizes: Immutable data over mutable data Pure functions over functions with side effects Expressions over statements
  • 3.
    Traditional imperative/object-oriented programming uses... Mutablestate/variables For loops over recursion Functions with side effects
  • 4.
    But...What if Itold you... You don't need for loops and mutable variables
  • 6.
    In order toavoid mutable variables, for loops, etc., functional programmers emphasize a few key concepts
  • 7.
    Pure functions No sideeffects Referential transparency - if it is called with the same arguments, it will always output the same value No data dependency between pure functions - order and parellelization will not effect how the function runs
  • 8.
    Recursion Can be usedin place of traditional looping Traditional application for a loop: summing a range function sumRange(start, end) { var total = 0; for (var i = start; i <= end; i++) total += i; return total; } sumRange(1, 10); // returns 55
  • 9.
    Now, with recursion... functionsumRange(start, end, acc) { return start > end? acc: sumRange(start + 1, end, acc + start); } sumRange(1, 10, 0); // also returns 55, but cooler
  • 10.
    But wait, recursionis slow! Not necessarily!
  • 11.
    Tail Call Optimization Implementedas of ES2015 ("ES6") ES2015 compilers can optimize tail recursive functions in strict mode What is a tail recursive function? A function whose main recursive call is in tail position (i.e., the recursive call is the last call in the function)
  • 12.
  • 13.
    But rst, alittle history... In the 1930's, mathmatician Alonzo Church invented Ξ» ("lambda") calculus, a model of computation based on function abstraction, variable binding and substitution This gave programmers a useful tool called the Ξ» function AKA the "anonymous function"
  • 14.
    In JavaScript, Ξ»functions are possible because functions are rst-class objects. They can be: Stored in variables Passed to functions Returned from functions This allows us to use a very cool functional programming technique called...
  • 15.
  • 16.
    Currying is afunctional programming technique that allows us to transform a function of arity (the number of arguments a function takes) N into a chain of N functions of arity 1 A currying function allows us to partially apply functions in a very useful, exible way: function sumThree(a, b, c) { return a + b + c; } var curriedSumThree = curry(sumThree); curriedSumThree(1)(2)(3); // 6 curriedSumThree(1,2)(3); // 6 curriedSumThree(1,2,3); // 6 curriedSumThree(1)(2,3); // 6
  • 17.
    ...how? ES2015 makes writinga curry function pretty straightfoward using arrow functions and the rest/spread syntax function curry(fn) { return function curried(...args) { return args.length >= fn.length ? fn.call(this, ...args) : (...rest) => { return curried.call(this, ...args, ...rest); }; }; } Source: http://www.datchley.name/currying-vs-partial-application/
  • 18.
    Ok...but why? It's cool DRY- Tiny, little, exible, reusable functions Because, with currying, we can very easily perform...
  • 19.
    Function composition Composition allowsus to put together functions in a compact, readible syntax that accurately re ects what we are trying to do with our code const add = (x, y) => x + y; const mult = (x, y) => x * y; const curriedAdd = curry(add); const curriedMult = curry(mult); const add2 = curriedAdd(2); const mult3 = curriedMult(3); const add2AfterMult3 = compose(add2, mult3); add2AfterMult3(4); // returns 14
  • 21.
    The compose function Recursion+ the rest/spread syntax allows us to express this very concisely const compose = (f, ...rest) => !rest.length? f: (...args) => f(compose(...rest)(...args));
  • 22.
    Limitations JavaScript is nota purely functional language. Among other things, it lacks: True immutability: even 'const' does not truly prevent you from mutating data, e.g.: Built-in function composition Automatically curried functions const user = {name: "johnson", number: 85}; user.name = "ochocinco"; // no error!
  • 23.
    Some functional JSlibraries lodash.js, underscore.js, lazy.js, ramda.js: Utility libraries that provide FP functionality, including composition and currying, as well as the usual suspects(map, reduce, lter, etc.). Lodash and Lazy.js are particularly interesting for their use of lazy evaluation, a concept associated with FP, to optimize performance immutable.js - Provides immutable data structures
  • 24.
    Purely functional languages Theseprovide enhanced functional programming features/performance, and often force you into a functional programming style Haskell Elm There are also many "impure" functional languages that are still "more" functional than JavaScript, including: Scala Clojure Lisp Erlang
  • 25.