Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Product of two number using HOC - JavaScript
Higher Order Functions (HOC) in JavaScript are functions that either receive another function as an argument or return a function as their result. When combined with closures, HOCs become a powerful tool for creating reusable and modular code.
In this example, we'll create a Higher Order Function that calculates the product of two numbers using the concept of currying, where a function returns another function.
Example
Here's how to implement a product calculator using HOC:
const num1 = 24;
const num2 = 5;
const productHOC = num1 => {
return product = num2 => {
return num1 * num2;
};
};
console.log(productHOC(num1)(num2));
120
How It Works
The productHOC function demonstrates currying:
- The outer function takes the first number (
num1) as a parameter - It returns an inner function that takes the second number (
num2) - The inner function has access to
num1through closure - When called with both arguments
productHOC(num1)(num2), it returns their product
Alternative Approach
Here's a more flexible version that can be reused multiple times:
const createMultiplier = multiplier => {
return number => multiplier * number;
};
const multiplyBy5 = createMultiplier(5);
const multiplyBy10 = createMultiplier(10);
console.log(multiplyBy5(24)); // 120
console.log(multiplyBy10(24)); // 240
console.log(multiplyBy5(8)); // 40
120 240 40
Key Benefits
- Reusability: Create specialized functions for different multipliers
- Closure: Inner function remembers the outer function's variables
- Currying: Break down multi-parameter functions into single-parameter functions
Conclusion
Higher Order Functions with closures enable elegant solutions for mathematical operations. This pattern is particularly useful for creating specialized functions that remember specific values, making your code more modular and reusable.
