In JavaScript, a higher-order function is a function that either takes another function as an argument or returns a function as a result. These functions are foundational to functional programming and enable clean, modular, and reusable code.
A higher-order function is:
This makes JavaScript a powerful language for functional programming.
Passing a function as an argument enables customizing behaviors.
Example: Array Iteration with forEach
const numbers = [1, 2, 3]; numbers.forEach(function(number) { console.log(number * 2); }); // Output: // 2 // 4 // 6
Returning functions allows creating flexible and reusable components.
Example: Function Factory
function createMultiplier(multiplier) { return function(number) { return number * multiplier; }; } const double = createMultiplier(2); console.log(double(5)); // Output: 10 const triple = createMultiplier(3); console.log(triple(5)); // Output: 15
JavaScript provides many higher-order functions in its standard library:
Transforms each element of an array.
const numbers = [1, 2, 3]; const squared = numbers.map(function(number) { return number * number; }); console.log(squared); // Output: [1, 4, 9]
Filters elements based on a condition.
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(function(number) { return number % 2 === 0; }); console.log(evenNumbers); // Output: [2, 4]
Reduces an array to a single value by applying a function.
const numbers = [1, 2, 3]; numbers.forEach(function(number) { console.log(number * 2); }); // Output: // 2 // 4 // 6
function createMultiplier(multiplier) { return function(number) { return number * multiplier; }; } const double = createMultiplier(2); console.log(double(5)); // Output: 10 const triple = createMultiplier(3); console.log(triple(5)); // Output: 15
const numbers = [1, 2, 3]; const squared = numbers.map(function(number) { return number * number; }); console.log(squared); // Output: [1, 4, 9]
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(function(number) { return number % 2 === 0; }); console.log(evenNumbers); // Output: [2, 4]
const numbers = [1, 2, 3, 4]; const sum = numbers.reduce(function(accumulator, currentValue) { return accumulator + currentValue; }, 0); console.log(sum); // Output: 10
Mastering higher-order functions is key to writing efficient and expressive JavaScript code.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
The above is the detailed content of Mastering Higher-Order Functions in JavaScript: Unlock Functional Programming. For more information, please follow other related articles on the PHP Chinese website!