Wednesday, February 19, 2025

JavaScript, Different ways to create higher order functions in JavaScript

What are different ways to create higher order functions in JavaScript. Give examples.
Answer: Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them. In JavaScript, you can create higher-order functions in several ways. Here are some examples:You can pass functions as arguments to other functions. This is commonly used in array methods like 'map', 'filter', and 'reduce'.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8]

const numbers = [1, 2, 3, 4];
const even = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(even); // Output: [2, 4]

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function(total, number) {
return total + number;
}, 0);
console.log(sum); // Output: 10
A higher-order function can also return another function.

function createGreeting(greeting) {
return function(name) {
return '${greeting}, ${name}!';
};
}
const sayHello = createGreeting('Hello');
console.log(sayHello('Alice')); // Output: Hello, Alice!
const sayGoodbye = createGreeting('Goodbye');
console.log(sayGoodbye('Bob')); // Output: Goodbye, Bob!
Higher-order functions can be used to combine multiple functions into one. This is often used in functional programming to create pipelines of functions.

function compose(f, g) {
return function(x) {
return f(g(x));
};
}
const add1 = x => x + 1;
const multiply2 = x => x * 2;
const add1ThenMultiply2 = compose(multiply2, add1);
console.log(add1ThenMultiply2(5)); // Output: 12
Currying is a technique of transforming a function with multiple arguments into a sequence of functions each with a single argument.

function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function(...args2) {
return curried.apply(this, args.concat(args2));
};
}
};
}
function add(a, b) {
return a + b;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)); // Output: 3
console.log(curriedAdd(1, 2)); // Output: 3
Higher-order functions can be used to create factories that generate functions with specific behaviors.

function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // Output: 10
const triple = multiplier(3);
console.log(triple(5)); // Output: 15
The 'forEach' method is another example of a higher-order function that takes a callback function as an argument.

const numbers = [1, 2, 3, 4];
numbers.forEach(function(number) {
console.log(number);
});
// Output:
// 1
// 2
// 3
// 4

These examples demonstrate various ways to create and use higher-order functions in JavaScript, allowing you to write more modular and reusable code.

No comments:

Post a Comment

Hot Topics