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:

  1. The outer function takes the first number (num1) as a parameter
  2. It returns an inner function that takes the second number (num2)
  3. The inner function has access to num1 through closure
  4. 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.

Updated on: 2026-03-15T23:18:59+05:30

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements