May 29, 2020
What is Function Currying in Javascript
In the following code, we first created single function add(a, b) which takes 2 arguments. Later, we made use of functional currying approach, to transform this function. The new function is add(a) which takes single argument and returns another function which again takes single argument. We are only going 1 level deep here, but as I said there is no limitation.
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; }
Javascript:
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); btnGet.addEventListener('click', () => { let add4 = add(4); let add6 = add(6); let add8 = add(8); result.innerText = add8(6); }); /* function add(a, b){ return a + b; } */ /* function add4(b){ return 4 + b; } function add6(b){ return 6 + b; } function add8(b){ return 8 + b; } */ function add(a){ return function(b) { return a + b; } }