CodeBlanks Logo Icon CodeBlanks

Currying

JavaScript course · Advanced · Lesson 57/100

Learn to turn a function into a chain that takes arguments one at a time.

Currying

Currying turns a single function into a chain that takes its arguments one at a time. A three-argument function becomes three nested functions, each taking one argument.

const add = a => b => c => a + b + c;
add(1)(2)(3); // 6

Each call returns the next function. The real computation does not happen until the final call. This shape makes it easy to bind arguments step by step and produce new functions.

Partial application

Partial application binds some arguments to a function in advance and produces a new function. Currying is a natural form of this idea.

const add = a => b => c => a + b + c;
const addOne = add(1); // b => c => 1 + b + c
addOne(2)(3); // 6

Here calling add(1) binds a and leaves a two-argument function behind. addOne is now a ready function that can be reused anywhere.

Exercise Write a curried multiply function

Write a curried function named multiply. It takes a, returns a function that takes b and returns a * b (a => b => a * b). Then call console.log(multiply(3)(4)).

Show example solution
const multiply = a => b => a * b;
console.log(multiply(3)(4));

Test yourself

  1. What does add(1)(2)(3) require?

    • A single function call
    • Nested returned functions
    • A Promise chain
    • A loop
    Show answer

    Nested returned functions — Correct! Each call returns the next function; nested returned functions are required.

  2. Bind the first argument

    const add = a => b => c => a + b + c;
    const addOne = add(____);
    Show answer
    const add = a => b => c => a + b + c;
    const addOne = add(1);
  3. Match the currying concepts

    currying
    arguments one by one
    partial application
    fixes some arguments
    a => b => c
    curry syntax

All lessons in Advanced