Saturday, June 29, 2024

Higher Order function in JavaScript



In JavaScript, a higher-order function is a function that does at least one of the following:
  1. Takes one or more functions as arguments.
  2. Returns a function as its result.
Higher-order functions are a key feature of functional programming and are widely used in JavaScript.

Note that because of HOF, JavaScript functions are first-class citizens because they can be used as argument and as return value of a function. In other words, JavaScript functions act as data/variables.

Examples of Higher-Order Functions
1. Functions as Arguments
Higher-order functions can take other functions as arguments. Common examples include array methods like map, filter, and reduce.
Example: Using map
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(n) {
  return n * 2;
});

console.log(doubled); // [2, 4, 6, 8, 10]
2. Functions as Return Values
Higher-order functions can also return functions. This is useful for creating function factories or for partial application.
Example: Function that Returns Another Function
function createMultiplier(multiplier) {
  return function(x) {
    return x * multiplier;
  };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15
3. Combining Functions
You can use higher-order functions to combine simple functions into more complex ones.
Example: Function Composition
function compose(f, g) {
  return function(x) {
    return f(g(x));
  };
}

function add1(x) {
  return x + 1;
}

function multiply2(x) {
  return x * 2;
}

const add1ThenMultiply2 = compose(multiply2, add1);
console.log(add1ThenMultiply2(5)); // 12
Practical Uses of Higher-Order Functions

1. Event Handling in Web Development
   Higher-order functions are commonly used in event handling. For instance, you might pass a callback function to an event listener.
  document.getElementById('button').addEventListener('click', function() {
     console.log('Button clicked!');
   });   
2. Asynchronous Programming
   They are also used in asynchronous programming with promises.
   fetch('https://api.example.com/data')
     .then(response => response.json())
     .then(data => {
       console.log(data);
     })
     .catch(error => {
       console.error('Error:', error);
     });
3. Functional Programming Paradigms
   Higher-order functions are essential in functional programming, allowing for more concise and readable code.
   const numbers = [1, 2, 3, 4, 5];
   const evenNumbers = numbers.filter(n => n % 2 === 0);
   console.log(evenNumbers); // [2, 4]
Conclusion:
Higher-order functions are a powerful feature in JavaScript, enabling more abstract and flexible code. They allow you to manipulate functions just like any other data type, leading to more modular and reusable code.

No comments:

Post a Comment

Hot Topics