What does the second set of parentheses after require in Node.js mean?

Today I am working with the code of colleagues and I have seen something that I have not seen before.

I understand the first part of the instruction (required in the clean.js file).

But what about the second set of parentheses?

require('./tasks/clean')('js', './dist/js')

      

+3


source to share


2 answers


Everything exported from ./tasks/clean

is a function, so it is simply called with 'js'

and './dist/js'

as parameters

This is equivalent to the following:



const clean = require('./tasks/clean');
clean('js', './dist/js');

      

+8


source


This syntax you are seeing is called Function currying , which is a popular technique when writing compositional functions in the functional programming paradigm. Currying and functional programming aren't new concepts, they've been around for decades, but functional programming is starting to get very popular in the JavaScript community.

Currying basically allows you to immediately call a function call from a function that returns a function.

Consider this function, which returns a function:

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

      

now when you call this function you can do the following:

foo(1)(2);

      

which will output to the console:



1
2

      

So, in the example you posted, the function clean()

should return a function that takes two parameters, for example:

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

      

which allows you to call it like this:

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

      

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

+2


source







All Articles