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)

  1. Functional programming, ↩︎

  2. Functional programming, ↩︎

  3. Functions, JavaScript Reference, ↩︎

  4. ES6 In Depth: Arrow functions, ↩︎

  5. Array, JavaScript Reference, ↩︎

  6. const keyword, JavaScript Reference, ↩︎

  7. Object.defineProperty, JavaScript Reference, ↩︎

  8. Iterators and generators, JavaScript Reference, ↩︎

  9. ECMAScript 6 Proper Tail Calls in WebKit, ↩︎

  10. ↩︎