WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 46 of 100

Can you explain the concept of "currying" in JavaScript and provide an example?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

In JavaScript, "currying" is a functional programming technique that involves transforming a function that takes multiple arguments into a series of functions that each take a single argument. This allows us to create more specialized functions that can be reused in different contexts.

Here’s an example of how to implement currying in JavaScript:

    // Define a function that takes multiple arguments
    function add(x, y, z) {
        return x + y + z;
    }
    
    // Create a curried version of the add function
    function curriedAdd(x) {
        return function(y) {
            return function(z) {
                return x + y + z;
            };
        };
    }
    
    // Use the curriedAdd function to add two numbers
    const add5 = curriedAdd(5);
    const result = add5(10)(15); // result = 30

In this example, we start with a function add that takes three arguments and returns their sum. We then define a new function curriedAdd that takes a single argument x and returns a new function that takes a single argument y, which in turn returns a new function that takes a single argument z. This creates a series of functions that can be composed together to add multiple numbers.

We then use the curriedAdd function to create a new function add5 that adds 5 to a number, and then call it with 10 and 15 to get a result of 30.

Currying can be a powerful technique for creating reusable functions that can be composed together in different ways. It allows us to create more specialized functions that are easier to reason about and can be used in a variety of contexts.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics