Function returning another function in JavaScript

In JavaScript, functions can be assigned to variables, passed as arguments to other functions, and returned from other functions. This behavior allows us to create higher-order functions (HOFs), which are functions that return other functions. These higher-order functions enable powerful patterns like callbacks, function memoization, and data transformation.

In this article, we will learn about functions returning other functions in JavaScript and explore practical examples of their usage.

Basic Function Returning Function

A function that returns another function creates a closure, where the inner function has access to the outer function's variables:

function createGreeter(greeting) {
    return function(name) {
        console.log(greeting + ", " + name + "!");
    };
}

const sayHello = createGreeter("Hello");
const sayHi = createGreeter("Hi");

sayHello("Alice");
sayHi("Bob");
Hello, Alice!
Hi, Bob!

Function Factory Pattern

Functions can return customized functions based on parameters, creating function factories:

function createMultiplier(factor) {
    return function(number) {
        return number * factor;
    };
}

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

console.log(double(5));  // 10
console.log(triple(4));  // 12

// Using with arrays
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(double);
console.log(doubled);
10
12
[2, 4, 6, 8]

Practical Example: Configuration Functions

Higher-order functions are useful for creating configurable operations:

function createValidator(minLength, pattern) {
    return function(input) {
        if (input.length < minLength) {
            return {valid: false, message: "Too short"};
        }
        if (pattern && !pattern.test(input)) {
            return {valid: false, message: "Invalid format"};
        }
        return {valid: true, message: "Valid"};
    };
}

// Create specific validators
const emailValidator = createValidator(5, /^[^\s@]+@[^\s@]+\.[^\s@]+$/);
const passwordValidator = createValidator(8, /^(?=.*[A-Za-z])(?=.*\d)/);

console.log(emailValidator("user@example.com"));
console.log(passwordValidator("password123"));
console.log(passwordValidator("weak"));
{valid: true, message: "Valid"}
{valid: true, message: "Valid"}
{valid: false, message: "Too short"}

Currying Example

Functions returning functions enable currying, where functions are called with one argument at a time:

function add(a) {
    return function(b) {
        return function(c) {
            return a + b + c;
        };
    };
}

// Usage
const result1 = add(1)(2)(3);
console.log(result1);

// Partial application
const addTwo = add(2);
const addTwoAndThree = addTwo(3);
const finalResult = addTwoAndThree(4);
console.log(finalResult);
6
9

Event Handler Generator

Create dynamic event handlers using function-returning functions:

function createClickHandler(message, count) {
    let clickCount = 0;
    
    return function() {
        clickCount++;
        console.log(message + " - Click " + clickCount);
        
        if (clickCount >= count) {
            console.log("Maximum clicks reached!");
            return true; // Could disable the handler
        }
        return false;
    };
}

// Create handlers with different configurations
const limitedHandler = createClickHandler("Button clicked", 3);

// Simulate clicks
console.log(limitedHandler()); // false
console.log(limitedHandler()); // false  
console.log(limitedHandler()); // true (max reached)
Button clicked - Click 1
Button clicked - Click 2
Button clicked - Click 3
Maximum clicks reached!
false
false
true

Common Use Cases

Use Case Description Benefit
Function Factories Create specialized functions Code reusability
Currying Partial function application Flexible function composition
Configuration Pre-configured operations Clean, maintainable code
Closures Private variables and state Data encapsulation

Conclusion

Functions returning other functions enable powerful programming patterns in JavaScript. They provide code reusability, enable function composition, and allow for elegant solutions to complex problems through closures and partial application.

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

780 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements