Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the second set of parentheses mean after a require statement in Node.js?

I'm working with a coworkers code today and I saw something I've never seen before.

I understand the first part of the statement (require in the file clean.js).

But what's with the second set of parentheses?

require('./tasks/clean')('js', './dist/js')
like image 491
Showcaselfloyd Avatar asked Mar 22 '17 18:03

Showcaselfloyd


2 Answers

Whatever is exported from ./tasks/clean is a function, so it's just being invoked with 'js' and './dist/js' as parameters

It is equivalent to the following:

const clean = require('./tasks/clean');
clean('js', './dist/js');
like image 114
Andrew Brooke Avatar answered Oct 05 '22 13:10

Andrew Brooke


This syntax you are seeing is called Function currying, which is a popular technique in writing composable functions in the Functional programming paradigm. Currying and Functional programming are not new concepts, they have been around for decades, but Functional programming is starting to get really popular with the JavaScript community.

Currying basically lets you immediately invoke a function call from a function that returns a function.

Consider this function that returns a function:

 function foo(x) {
   console.log(x);
   return function(y) {
     console.log(y);
   }
 }

now when calling this function, you can now do this:

foo(1)(2);

which will output to the console:

1
2

So in the example that you posted, the clean() function must return a function that accepts two parameters, like this:

function clean(a) {
   return function(b, c) {
     console.log(a, b, c);
   }
}

which allows it to be called like this:

clean('foo')('bar', 'baz');
//=> 'foo' 'bar' 'baz'

This was a super basic example, but I hope this helps!

like image 40
radiovisual Avatar answered Oct 05 '22 12:10

radiovisual