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! πŸš€

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay