Function composition is a core concept in functional programming that involves combining two or more functions to form a new function. The resulting function allows data to flow through the composed functions as a pipeline, enhancing code modularity and reusability.
Function composition involves creating a new function by sequentially applying other functions. The output of one function becomes the input for the next. Here’s a basic example:
In this example, incrementAndDouble
first increments the input by 1, then doubles it. This composition is done using the compose
function, which takes two functions f
and g
, and creates a new function where g
is applied before f
.
Consider a scenario where we need to process text data:
In this composed function, prepareText
, the input string is first trimmed, converted to lowercase, and finally wrapped within a <div>
tag. The composition streamlines the function chaining, making it clear and linear.
For more complex scenarios involving multiple functions, you can create a more versatile compose
utility:
This version of compose
uses reduce
to apply all provided functions, allowing an arbitrary number of functions to be composed. This is useful for creating flexible pipelines that transform data through various stages.
To deepen your understanding of function composition in JavaScript, you may explore libraries such as Lodash or Ramda that offer built-in utilities for function composition.
Function composition in JavaScript provides a powerful way to structure and organize code following functional programming principles, facilitating the creation of more predictable and maintainable software.