Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two sets of parentheses in a JavaScript function call? [duplicate]

I'm reading a book on Node.js and Express in one of the examples shows a function call with two sets of parentheses. I was hoping for an explanation of what the code is doing since I haven't seen this before. Here's the code:

app.use(require('cookie-parser')(credentials.cookieSecret));

Again, the part that's confusing me is the second set of parans which seems to be passing "credentials.cookieSecret" as an argument, but to what? It looks similar to an IIFE but I'm don't it is.

Thanks.

like image 268
Rey Bango Avatar asked Mar 14 '23 15:03

Rey Bango


2 Answers

cookie-parser module returns a function, which is getting called in the code you shared.

app.use(require('cookie-parser')(credentials.cookieSecret));

could be rewritten as:

var cookieParser = require('cookie-parser')

var cookieParserInstance = cookieParser(credentials.cookieSecret)

app.use(cookieParserInstance)
like image 162
Mehdi Avatar answered Apr 08 '23 12:04

Mehdi


It happens if the function returns another function.

Here an example:

var increment = function(base){
    return function(adding){
      return base + adding;
    };
}

var sum = increment(2)(3); // sum = 5

that is

var setBase = increment(2); // setBase = function(adding){ return 2 + adding; }
var sum = setBase(3);
like image 42
squaleLis Avatar answered Apr 08 '23 14:04

squaleLis