Functional JS: Functors

· 314 words · 2 minute read

Let’s review one of the most interesting concepts within functional programming.

Functors are one of the most interesting concepts in functional programming. Although their name might be misleading, they are actually more of a data type than a function itself. Functors are objects that follow certain specific characteristics.

The key concept behind functors is that they are objects that implement the map method, which takes a function as an argument and applies it to the data it contains for transformation. This transforming function returns a new object of the same type and structure as the original, but with the values transformed by the provided function.

A common example of a functor in JavaScript is the array. Arrays implement the map method, which takes a function that is applied to all of its elements and returns a new array with the transformed data. For example:

const myArray = [1, 2, 3, 4, 5];
const myTransformedArray = myArray.map((x) => x * x);

// myTransformedArray = [1, 4, 9, 16, 25];

This new array (myTransformedArray) is the result of applying a function in map, and it’s also a functor because it implements map.

The importance of functors lies in their ability to provide safer and more robust data handling, as well as enabling function composition. For example, we can chain multiple calls to map to perform chained transformations in a clear and concise manner.

const myArray = [1, 2, 3, 4, 5];
const myTransformedArray = myArray
  .map((x) => x * x)
  .map((x) => x + 1)
  .map((x) => (x % 2 === 0 ? false : true));

In summary, functors have the following characteristics:

  • Functors are objects, not primitive types.
  • Functors are objects that implement the map function.
  • The map function takes a function as an argument to use for transformation.
  • The map function returns an object of the same shape and structure as the original object.