JavaScript Currying for Beginners: A Practical Introduction

JavaScript Currying for Beginners: A Practical Introduction

Currying has always been a challenging concept for me, especially when interviewers ask about it. I often struggled to provide a clear answer to this question. It’s an important topic that frequently comes up in JavaScript interviews for candidates with 2 or more years of experience. Since I’ve been working in the industry for the past two years, I’d like to help you understand this topic in a beginner-friendly way. Lastly, I have added a bonus question for an interview so read that especially. If you find it helpful and if you’re feeling extra generous, you can always buy me a ☕️

What Is Currying?

In simple words it is a pattern in functional programming in which a function which is taking multiple arguments into a nested series of functions, each taking a single argument.

Confused right? hahaha, I was also when I first read that on the internet but don’t worry we will learn it in a more simplified way.

Explanation.

Now suppose you have a function that takes multiple arguments and then sums it.

function add(a,b){
  return a+b
}

Now in currying what we do is that we transform that function and break it down into a series of functions that each take one argument.

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

const addFive = add(5); 
const result = addFive(3);

In the example above, we transformed a function so that we could call it by passing one argument at a time and getting the final sum at the end.

Now, you might be wondering, “Why would we do this? Why make a simple function seem more complicated?” I used to have the same question, but for now, let’s focus on the “how” rather than the “why.” Specifically, how does this function remember the number from the previous execution? Let’s dive into that aspect.

Behind The Scene Magic?

In job interviews, explaining how currying works in JavaScript can make a good impression. The reason it works is because of something called “closure.” To put it simply, closure lets an inside function remember things from an outside function, even after the outside function is finished.

Think of it this way: The inside function, which adds the second number, ‘remembers’ the first number because of closure. It holds onto what happened in the outside function. So, when we use it later with the second number, it still knows what the first number was.

In interviews, confidently saying that closures make this happen can impress your interviewer. You don’t have to get into complex tech stuff — just mention that closures are the secret to this. With this understanding, you’ll be ready to talk about this topic with ease.

Why Should We Use Currying in JavaScript?

  1. Code re-usability

curried functions are like reusable building blocks. Once you create a curried function, you can use it in various places with different arguments. This reusability can save you time and reduce code duplication.

2. Writing High Order Function In Javascript

Currying is often used in the context of writing higher-order functions. Higher-order functions are functions that take other functions as arguments or return functions as results. Currying is a technique that can help in creating and working with higher-order functions effectively.

3. Code Readability
Currying helps break down complex functions into smaller, more manageable parts. Just like you add ingredients one by one, you can apply functions step by step, making your code easier to understand and maintain.

4 . Functional Programming

Currying is a fundamental concept in functional programming, a programming style that emphasizes the use of functions as first-class citizens. If you’re into functional programming, currying is a valuable tool to have in your toolkit.

Bonus Interview Question

Write a function that takes a simple function and converts it into a currying function.
Now let's see the code first. The catch is you can call it in the curried way or a normal way and we can call it a partial curried way like 2 args at the same time and 1 different.

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn(...args);
    } else {
      return function (...moreArgs) {
        return curried(...args, ...moreArgs);
      };
    }
  };
}

// Example normal function
function add(a, b, c) {
  return a + b + c;
}

// Convert the function into a curried version
const curriedAdd = curry(add);

// Usage
console.log(curriedAdd(1)(2)(3)); // Output: 6
console.log(curriedAdd(1, 2)(3)); // Output: 6
console.log(curriedAdd(1)(2, 3)); // Output: 6
console.log(curriedAdd(1, 2, 3)); // Output: 6

In this code, the curry function takes a simple function fn as an argument and returns a curried function. The curried function keeps track of the arguments using the args array and checks whether it has enough arguments to call the original function. If not, it returns a new curried function with the updated arguments, allowing for partial curried calls or combining different argument sets.

Conclusion

I hope you understand currying at a beginner’s level. I’m aware that there are many concepts surrounding it, and we’ll delve into those in future blog posts.

Thank you for taking the time to read this post. If you have any questions or would like to connect, feel free to reach out to me on LinkedIn. Do follow my YouTube channel for more content like that.

Did you find this article valuable?

Support Muhammad Younus by becoming a sponsor. Any amount is appreciated!