|
| 1 | +# Higher Order Functions in JavaScript |
| 2 | + |
| 3 | +## What is a Higher Order Function? |
| 4 | +A higher order function is a function that either: |
| 5 | +- Takes one or more functions as arguments |
| 6 | +- Returns a function as its result |
| 7 | +for eg. |
| 8 | + |
| 9 | +```js |
| 10 | +function x() { |
| 11 | + console.log("Hi"); |
| 12 | +}; |
| 13 | +function y(x) { |
| 14 | + x(); |
| 15 | +}; |
| 16 | +y(); // Hi |
| 17 | +// y is a higher order function |
| 18 | +// x is a callback function |
| 19 | +``` |
| 20 | + |
| 21 | +## Why use Higher Order Functions? |
| 22 | +- **Abstraction:** Hide details and expose only necessary parts |
| 23 | +- **Reusability:** Write generic functions that work with other functions |
| 24 | +- **Functional Programming:** Enables techniques like map, filter, reduce |
| 25 | + |
| 26 | +## Examples |
| 27 | + |
| 28 | +### 1. Passing a function as an argument |
| 29 | +```js |
| 30 | +function greet(name) { |
| 31 | + return `Hello, ${name}!`; |
| 32 | +} |
| 33 | +function processUserInput(callback) { |
| 34 | + const name = 'Aditya'; |
| 35 | + return callback(name); |
| 36 | +} |
| 37 | +console.log(processUserInput(greet)); // Output: Hello, Aditya! |
| 38 | +``` |
| 39 | + |
| 40 | +### 2. Returning a function |
| 41 | +```js |
| 42 | +function multiplier(factor) { |
| 43 | + return function(number) { |
| 44 | + return number * factor; |
| 45 | + }; |
| 46 | +} |
| 47 | +const double = multiplier(2); |
| 48 | +console.log(double(5)); // Output: 10 |
| 49 | +``` |
| 50 | + |
| 51 | +### 3. Built-in Higher Order Functions |
| 52 | +There are various built in HOFs, and some of the most common ones are map(), filter() and reduce(). |
| 53 | + |
| 54 | +- **map** is a method that we use to apply a function to each element in an array, and it returns a new array with the modified elements. |
| 55 | + |
| 56 | +- The **filter()** function takes an array and returns a new array with only the values that meet certain criteria. It also does not mutate the original array. It is often used to select a subset of data from an array based on certain criteria. |
| 57 | + |
| 58 | +- The **reduce()** method in JavaScript is an array method that executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The result is a single output value. |
| 59 | + |
| 60 | +```js |
| 61 | +const numbers = [1, 2, 3, 4, 5]; |
| 62 | +const squares = numbers.map(x => x * x); // [1, 4, 9, 16, 25] |
| 63 | +const evens = numbers.filter(x => x % 2 === 0); // [2, 4] |
| 64 | +const sum = numbers.reduce((acc, curr) => acc + curr, 0); // 15 |
| 65 | +``` |
| 66 | + |
| 67 | +### 4. Custom Higher Order Function Example |
| 68 | +```js |
| 69 | +// repeat is a higher order function because it takes another function (action) as an argument |
| 70 | +function repeat(n, action) { |
| 71 | + for (let i = 0; i < n; i++) { |
| 72 | + action(i); // action is called for each value of i |
| 73 | + } |
| 74 | +} |
| 75 | +// Here, console.log is passed as the action, so it logs 0, 1, 2 |
| 76 | +repeat(3, console.log); // Logs 0, 1, 2 |
| 77 | +``` |
| 78 | + |
| 79 | +### 5. Returning Functions (Closures) |
| 80 | +```js |
| 81 | +// makeCounter returns a function, so it's a higher order function |
| 82 | +// The returned function forms a closure over the count variable |
| 83 | +function makeCounter() { |
| 84 | + let count = 0; |
| 85 | + return function() { |
| 86 | + count++; // count is remembered between calls |
| 87 | + return count; |
| 88 | + }; |
| 89 | +} |
| 90 | +const counter = makeCounter(); |
| 91 | +console.log(counter()); // 1 |
| 92 | +console.log(counter()); // 2 |
| 93 | +// Each call to counter() increases and returns the count |
| 94 | +``` |
| 95 | + |
| 96 | +### 6. Function Composition |
| 97 | +```js |
| 98 | +// compose is a higher order function that takes two functions and returns a new function |
| 99 | +function compose(f, g) { |
| 100 | + return function(x) { |
| 101 | + return f(g(x)); // applies g to x, then f to the result |
| 102 | + }; |
| 103 | +} |
| 104 | +const add1 = x => x + 1; |
| 105 | +const times2 = x => x * 2; |
| 106 | +const add1ThenTimes2 = compose(times2, add1); |
| 107 | +console.log(add1ThenTimes2(5)); // (5 + 1) * 2 = 12 |
| 108 | +// add1ThenTimes2 first adds 1 to 5, then multiplies the result by 2 |
| 109 | +``` |
| 110 | + |
| 111 | +## Interview Approach Example: Calculating Area and Circumference |
| 112 | + |
| 113 | +### First Approach (Not DRY) |
| 114 | +```js |
| 115 | +const radius = [1, 2, 3, 4]; |
| 116 | +const calculateArea = function (radius) { |
| 117 | + const output = []; |
| 118 | + for (let i = 0; i < radius.length; i++) { |
| 119 | + output.push(Math.PI * radius[i] * radius[i]); |
| 120 | + } |
| 121 | + return output; |
| 122 | +}; |
| 123 | +console.log(calculateArea(radius)); |
| 124 | + |
| 125 | +const calculateCircumference = function (radius) { |
| 126 | + const output = []; |
| 127 | + for (let i = 0; i < radius.length; i++) { |
| 128 | + output.push(2 * Math.PI * radius[i]); |
| 129 | + } |
| 130 | + return output; |
| 131 | +}; |
| 132 | +console.log(calculateCircumference(radius)); |
| 133 | +``` |
| 134 | + |
| 135 | +### Better Approach Using Higher Order Function |
| 136 | +```js |
| 137 | +const radiusArr = [1, 2, 3, 4]; |
| 138 | + |
| 139 | +// logic to calculate area |
| 140 | +const area = function (radius) { |
| 141 | + return Math.PI * radius * radius; |
| 142 | +} |
| 143 | + |
| 144 | +// logic to calculate circumference |
| 145 | +const circumference = function (radius) { |
| 146 | + return 2 * Math.PI * radius; |
| 147 | +} |
| 148 | + |
| 149 | +const calculate = function(radiusArr, operation) { |
| 150 | + const output = []; |
| 151 | + for (let i = 0; i < radiusArr.length; i++) { |
| 152 | + output.push(operation(radiusArr[i])); |
| 153 | + } |
| 154 | + return output; |
| 155 | +} |
| 156 | +console.log(calculate(radiusArr, area)); |
| 157 | +console.log(calculate(radiusArr, circumference)); |
| 158 | +// Over here calculate is HOF |
| 159 | +// Over here we have extracted logic into separate functions. This is the beauty of functional programming. |
| 160 | + |
| 161 | +// We can also use built-in higher order functions like map to achieve the same result |
| 162 | +const areas = radiusArr.map(area); |
| 163 | +console.log(areas); |
| 164 | +const circumferences = radiusArr.map(circumference); |
| 165 | +console.log(circumferences); |
| 166 | + |
| 167 | +``` |
| 168 | + |
| 169 | +### Polyfill of map (Custom Implementation) |
| 170 | +```js |
| 171 | +// Over here calculate is nothing but polyfill of map function |
| 172 | +// console.log(radiusArr.map(area)) == console.log(calculate(radiusArr, area)); |
| 173 | + |
| 174 | +Array.prototype.calculate = function(operation) { |
| 175 | + const output = []; |
| 176 | + for (let i = 0; i < this.length; i++) { |
| 177 | + output.push(operation(this[i])); |
| 178 | + } |
| 179 | + return output; |
| 180 | +} |
| 181 | +console.log(radiusArr.calculate(area)); |
| 182 | +``` |
| 183 | + |
| 184 | +## Summary |
| 185 | +Higher order functions are a key concept in JavaScript, enabling powerful patterns for abstraction, reusability, and functional programming. |
0 commit comments