Skip to content

Currying in JavaScript Explained: Practical Example & Interview Guide

What is Currying in JavaScript: A Practical Guide (Interview Question)

This video provides a clear and practical explanation of currying in JavaScript, a common interview topic. It demonstrates the concept itself and a real-world use case for sending emails, contrasting it with regular functions and manual variable collection.

Keywords: currying in JavaScript, JavaScript currying, functional programming, closures, higher-order functions, JavaScript coding interview

What is Currying?

The video begins by explaining currying using a simple add function that takes three parameters (a, b, c) and returns their sum.

  • Normal Function: add(2, 5, 10) immediately executes and returns the sum.
  • Curried Function: Instead of returning the sum directly, it returns a series of nested functions, each taking one argument.
function add(a) {
  return function(b) {
    return function(c) {
      return a + b + c;
    }
  }
}

This allows you to call the function step-by-step: add(2)(5)(10). The final addition only happens when all three arguments are provided.

Why Use Currying?

The key advantage is that a function is only executed when all its arguments are available. This is useful when data comes from different sources (e.g., API calls, user input).

Instead of manually collecting three variables and checking if all are present before calling the function, currying handles this automatically. The function simply doesn't execute until the last argument is passed.

Practical Example: Sending Automated Emails

The video provides a real-world scenario: an automated email sending system with three parameters:

  1. To (recipient address)
  2. Subject
  3. Body

These parameters might be collected by different developers or at different times.

Without Currying

You would need to manually collect all three pieces of data in variables and then call a single function, which is not scalable for many parameters.

With Currying

The sendAutoEmail function is curried:

const sendAutoEmail = (to) => (subject) => (body) => `Sending email to ${to} with subject ${subject} and body ${body}`;

Now, different developers can handle their part:

  1. Developer 1 (Handles the 'To' address):
    const step1 = sendAutoEmail('[email protected]');
    
  2. Developer 2 (Handles the 'Subject'):
    const step2 = step1('New Order Confirmation');
    
  3. Developer 3 (Handles the 'Body'):
    const result = step2('Your order has been placed.');
    console.log(result);
    // Output: Sending email to [email protected] with subject New Order Confirmation and body Your order has been placed.
    

Each developer works on their own part, and the email is only sent when all three arguments are provided.

Modern Syntax for Currying

The video also shows how to write curried functions more concisely using arrow functions:

// Traditional
const add = (a) => (b) => (c) => a + b + c;

// For the email example
const sendAutoEmail = (to) => (subject) => (body) => `Sending email to ${to} with subject ${subject} and body ${body}`;

Key Takeaways

  • Currying transforms a function that takes multiple arguments into a sequence of nested functions, each taking a single argument.
  • Core Benefit: A function is executed only when all arguments are available, making it ideal for data collected from multiple sources.
  • Foundation: Currying is built on closures (a function returning a function).
  • Practical Use: It's a powerful technique in functional programming and is frequently asked about in JavaScript interviews. For additional common interview challenges, also see Top 30 JavaScript Interview Questions with Expert Answers.

Keep this summary

Save it to LunaNotes and it becomes a real note in your library тАФ editable, searchable, and ready to turn into flashcards or a diagram. Free to start.

Save to LunaNotes

Or summarise for another video.

32K+ people have turned 65K+ videos into notes

тАЬVery useful tool. I'm using it for the last couple weeks and I'm loving it so far. Makes learning on YouTube a great experience.тАЭ
Bhai Chrome Web Store review

This summary and transcript were automatically generated using AI with the Free YouTube transcript summary tool by LunaNotes.

Related summaries

Hoisting in JavaScript: Namaste JavaScript ЁЯФе Magic Behind Scopes

Hoisting in JavaScript: Namaste JavaScript ЁЯФе Magic Behind Scopes

Learn the true magic of JavaScript hoisting тАФ how variables and functions are accessible before initialization. This in-depth tutorial explains the execution context, the difference between undefined vs not defined, and how the call stack works behind the scenes.

Top 30 JavaScript Interview Questions with Expert Answers

Top 30 JavaScript Interview Questions with Expert Answers

Master JavaScript interviews with this comprehensive guide featuring 30 commonly asked questions ranging from basics to advanced concepts. Gain insights on topics like hoisting, closures, promises, async/await, event delegation, and more, supported by clear examples and best practices for both beginners and experienced developers.

.NET Full-Stack Interview: C#, SQL, Web API & React Concepts Explained

.NET Full-Stack Interview: C#, SQL, Web API & React Concepts Explained

In this mock interview, a full-stack developer with 3.5 years of experience is quizzed on key .NET, SQL, and React concepts. Topics covered range from C# fundamentals like IEnumerable vs IQueryable and async/await, to SQL indexing and normalization, as well as Web API middleware and React hooks.

JavaScript Complete Beginner to Advanced: Need, Origin & Node.js Setup

JavaScript Complete Beginner to Advanced: Need, Origin & Node.js Setup

This video kicks off a comprehensive JavaScript series, explaining why JavaScript was created in 1995 despite existing languages like C++ and Java. It covers the need for a secure, lightweight, easy-to-learn language for web interactivity and provides a first-principles thinking approach to understand the JavaScript engine, V8, and how to set up Node.js on your system.

Python Functions: Reusable Logic and Code Organization Basics

Python Functions: Reusable Logic and Code Organization Basics

Learn how to create and use Python functions to package logic into reusable blocks. This lesson covers function definition, parameters, return values, and how functions combine with loops to build structured programs.

Found this summary useful?

Take it with you. One click puts it in your own LunaNotes library.

Save to LunaNotes

Start taking better notes today with LunaNotes