Site icon JD Bots

How to Call a Function That Returns a Function in JavaScript

Card titled Functions That Return Functions, labelled JavaScript basics, with four ticked lines: multiplier(3) gives a function, triple(5) gives 15, and multiplier(2)(21) gives 42.

How to Call a Function That Returns a Function in JavaScript

In JavaScript, a function is a value like any other, so a function can give back another function. You then call the function it gave back, either later by a name you store it under, or straight away with a second pair of brackets: f(a)(b).

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

Syntax

const inner = outer(a);
inner(b);

outer(a)(b);

See First-class function and Closures on MDN.

Prerequisites

The Example

A function, multiplier, that takes a factor and gives back a function that multiplies a number by it. It’s in a file named returns-function.js.

Step 1: Write the Code

returns-function.js

function multiplier(factor) {
  return (n) => n * factor;
}

const triple = multiplier(3);
console.log(triple(5));
console.log(multiplier(2)(21));

Step 2: Run It

Terminal

node returns-function.js

Output

15
42

multiplier(3) gave back a function, stored as triple, and triple(5) gave 15. multiplier(2)(21) did both calls in one line and gave 42.

Common Mistakes

MistakeWhat happensDo this instead
Passing both values to the first call: multiplier(2, 21)The 21 is ignored, and you get the function itself. Printing it showed [Function (anonymous)]Call the result: multiplier(2)(21)

FAQ

How does the inner function still know the factor?

It keeps access to the values around it when it was made, here factor. This is called a closure.

Where would I see f(a)(b) in real code?

Libraries use it to set something up in the first call and finish it in the second. TanStack Router’s createFileRoute('/about')({ … }) is one example.

Conclusion

When a function gives back a function, call the result: store it and call it later, or write outer(a)(b) to do both at once.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

Exit mobile version