DEV Community

Cover image for Currying Step-By-Step
Vasil Vasilev
Vasil Vasilev

Posted on • Edited on

Currying Step-By-Step

Definition

Transform a function that takes multiple arguments into a series of functions that take a single argument each.

Reason

The main advantage of currying is that the new function can be partially applied to its arguments.

Instead of:

function sum(x, y, z) { 
    return x + y 
} 
sum(1, 2, 3); //LOGs: 6
Enter fullscreen mode Exit fullscreen mode

We have:

function sum(x) { 
    return (y) => { 
        return (z) => { 
            return x + y + z;
        } 
    } 
} 
sum(1)(2)(3); //LOGs: 6
Enter fullscreen mode Exit fullscreen mode

Although currying can be achieved via other techniques, for example .bind(), this article focuses on utilizing closures.
Closures enables us to allocate each closure for a returned function to a specific variable:

function sum(x) { 
    return (y) => { 
        return (z) => { 
            return x + y + z;
        } 
    } 
} 
const addOne = sum(1)
const addTwo = addOne(2)
console.log(addTwo(3)) //LOGs: 6
Enter fullscreen mode Exit fullscreen mode

1. When execution of the code comes to "const addOne = sum(1)", JS creates a closure for the returned function that captures the value of x as 1 in the Heap memory:

In HEAP: x = 1

In Stack:
(y) => { 
        return (z) => { 
            return x(1) + y + z;
        } 
    } 

Enter fullscreen mode Exit fullscreen mode

2. when execution of the code comes to "const addTwo = add(2)", JS creates a closure for the returned function that captures the value of y as 2 in the Heap memory:

In HEAP: x = 1, y = 2

In Stack:
(z) => { 
            return x(1) + y(2) + z;
        } 

Enter fullscreen mode Exit fullscreen mode

3. when execution of the code comes to "console.log(addTwo(3))", JS creates a closure for the returned function that captures the value of z as 2 in the Heap memory:

In HEAP: x = 1, y = 2, z = 3;

In Stack:
x(1) + y(2) + z(3);
Enter fullscreen mode Exit fullscreen mode

All that is left is the execution of the final return:

function sum(1) { 
    return (2) => { 
        return (3) => { 
            return 1 + 2 + 3;
        } 
    } 
} 
const addOne = sum(1)
const addTwo = addOne(2)
console.log(addTwo(3)) //LOGs: 6
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs