June 2, 2020
What is Function Composition in Javascript
In function composition, we have a single parent function. Outside parent function, we create multiple small functions which may or may not serve single purpose. Then, these small functions are called one by one inside single parent function. Value returned by one function is passed on to another and so on until we have final output which will be returned by our single parent function.
In the following code, we have single parent function addAndSquare() and 2 small functions add() and square(). The add() function only return sum of 2 numbers and square() function only returns square of a number. Thus, they both are serving single purpose. Value returned by add() function is passed on to the square() function and after both of these functions are executed, we are returning final output. I hope it clears the confusion.
HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <button>Get</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
CSS:
body { text-align: center; } div { display: inline-block; } button { display: inline-block; padding: 10px 20px; }
Javascript:
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); btnGet.addEventListener('click', () => { result.innerText = addAndSquare(3,2); }); function add(x, y){ return x + y; } function square(z){ return Math.pow(z,2); } function addAndSquare(a,b){ let total = add(3,2); return square(total); }