DEV Community

Aditya Singh
Aditya Singh

Posted on

Higher Order Functions in JS! πŸ’»βœ¨

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
Enter fullscreen mode Exit fullscreen mode

This runs the callback function after 5000ms! ⏲️

2️⃣ Using map

let numbers = [1, 2, 3, 4];
numbers.map(number => number * 10);
Enter fullscreen mode Exit fullscreen mode

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]

Enter fullscreen mode Exit fullscreen mode

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)