Mastering Currying in JavaScript​: Beyond .bind() and Into Functional Power

Mastering Currying in JavaScript: Beyond .bind() and Into Functional Power

Recently, I learned about a powerful concept in JavaScript called currying, and it completely changed the way I think about writing functions.

How It Started

I first discovered currying through a video by Akshay Saini Sir, who explained it using the .bind() method and closures. His teaching style made the concept incredibly easy to understand for beginners.

Watch the video here - It's a must-watch if you're exploring functional programming in JavaScript!


In that video, Akshay introduced the concept using the .bind() method, which initially made it super intuitive to grasp.

Here's a quick recap:

function multiply(x, y) {
  console.log(x * y);
}

const multiplyByTwo = multiply.bind(this, 2);
console.log(multiplyByTwo(5)); // Output: 10        

At first glance, this looked like currying to me, and honestly, it’s a brilliant stepping stone to understanding the concept.


But .bind() is Not True Currying

After diving deeper, I realized that .bind() is actually an example of partial application, not full currying.

Here's why:

  1. .bind() returns a function with some arguments pre-filled.
  2. But it doesn’t allow chaining one argument at a time, which is a core idea of currying.
  3. It’s fixed to the number of arguments you predefine.


What Is True Currying?

Currying transforms a function with multiple arguments into a series of functions that each take one argument at a time.

Example

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

add(1)(2)(3); // Output: 6        

This opens the door to modular, reusable, and composable functions.


A Reusable curry() Utility

Here’s a real curry() function that works dynamically:

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

Usage

function sum(a, b, c) {
  return a + b + c;
}

const curriedSum = curry(sum);

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

Final Thoughts

Thanks to Akshay Saini Sir's video, I was able to step into the world of currying with a real-world relatable example using .bind(). From there, digging deeper helped me uncover the full power of currying in JavaScript.

Whether you're building utilities, writing clean abstractions, or just curious about functional programming, currying is a concept worth mastering.

"Tide, time, and JavaScript wait for none!" - Akshay Saini

To view or add a comment, sign in

Explore content categories