Functional Concepts in JavaScript
The following list of features is frequently used to attribute the functional languages[1][2]:
- Higher-order functions - the functions that take other functions as their arguments;
- Purity - absence of side effects;
- Recursion - availability of tail-call optimisation.
The high-order functions are in JavaScript since its first version[3]. The arrow function syntax, introduced in ECMAScript 6[4], allowed to write the function constructs more easily and improved readability of the code. The iterative array methods[5] (forEach
, map
, reduce
, etc) eliminated necessity of mutating loop counter (index) to go through the lists. const
[6] added concept of "readonly" variables. Readonly properties[7] made immutable records possible. Generators and improved iterators[8] provided a way to create immutable iterable data sets. The most recent addition to the set of functional features is optimisation of tail recursion[9], now available in some of JS engines[10].
Although it was possible to create pure functions in earlier JS versions, the recent additions to the language added methods to create immutable data structures and provided ways to avoid using mutable variables for basic operations.
// toInt is a pure function that converts strings
// to integers. It does it by partially applying
// parseInt function, fixing its second argument.
let toInt = x => parseInt(x, 10);
// apply is a high-order pure function
let apply = (f, x) => f(x);
// it applies the first argument to the second
apply(toInt, "16"); // 16 (integer)
Functional programming, https://wiki.haskell.org/Functional_programming ↩︎
Functional programming, https://en.wikipedia.org/wiki/Functional_programming ↩︎
Functions, JavaScript Reference, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions ↩︎
ES6 In Depth: Arrow functions, https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/ ↩︎
Array, JavaScript Reference, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array ↩︎
const keyword, JavaScript Reference, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const ↩︎
Object.defineProperty, JavaScript Reference, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty ↩︎
Iterators and generators, JavaScript Reference, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ↩︎
ECMAScript 6 Proper Tail Calls in WebKit, https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit/ ↩︎
https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation) ↩︎