JavaScript Function Composition: What is Composition Function?

ยท

2 min read

Function Composition:

Just like real function in Mathematics that looks like f(x) so also this is found in programming languages like JavaScript.

JavaScript according to Wikipedia is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. Over 97% of websites use JavaScript on the client-side for web page behaviour, often incorporating third-party libraries.

Function Composition is the combination of several functions into a smaller function. It is also an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result. Function compositions can be composed of any number of functions. Or better still, the composition function takes any number of functions and invokes them all one after the other.

function add (a, b) {
  return a + b;
}

add(2, 3)

// output: 5

The above code snippet is a simple form to write a function in JavaScript. That being done, let's create several functions to the very end we have a smaller function in order to achieve function composition.

var addTwo = (a) => {
 return a + 2;
}

var addThree = (b) => {
 return b + 3;
}

addTwo(addThree(2))

// output: 7

addTwo function takes a value of a while addThree is a function that takes a value of b. Composing the two functions together JavaScript performs firstly the statement of a function that is inside another function i.e addThree function, the statement is b (which is 2 in this case), return 2 + 3 which results in 5.

Now, we have addTwo(5) since the addThree function has been performed.

addTwo(5) performs the function by adding two (2) to 5 which gives 7 hence our result.

Importance of Composition Function

There is importance to the usage of composition function which is the reusability of functionality at a very high level.

Libraries for function composition

  1. Lodash: One of the most popular libraries used by developers today. It is a JavaScript library that provides utility functions for common programming tasks using the functional programming paradigm.

  2. Ramda: A practical functional library for JavaScript programmers.

These libraries can be used to avoid implementing either function so you can focusโ€‹ on its uses of it.