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')
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');
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With