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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay