A Higher Order Function is a function that takes another function as an argument, returns a function, or both. Letβs see some examples! π
1οΈβ£ Classic Example: setTimeout
setTimeout(() => { console.log('Runs after 5000ms!'); }, 5000); // Best example of higher order function
This runs the callback function after 5000ms! β²οΈ
2οΈβ£ Using map
let numbers = [1, 2, 3, 4]; numbers.map(number => number * 10);
Transforms each element in the array by multiplying by 10! π
3οΈβ£ Custom Example: applyOperation
function applyOperation(arr, operation) { return arr.map(operation); } let numbers = [1, 2, 3, 4]; let squaredNumbers = applyOperation(numbers, number => number * number); console.log(squaredNumbers); // [1, 4, 9, 16]
This higher-order function takes an array and a function (operation) to apply to each element! π
π Key Takeaway: Higher Order Functions make your code more flexible and powerful! Start using them to simplify your code today! π
Top comments (0)