Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does double parentheses mean in a require

I know what this require statement does.

var express = require('express'); var app = express(); 

But sometimes i have seen two parentheses after the require.

var routes = require('./routes')(app); 

Q) What does this mean, and how does it work?

like image 750
Anders Östman Avatar asked Jun 04 '14 18:06

Anders Östman


People also ask

How do you use double parentheses?

1. Use brackets inside parentheses to create a double enclosure in the text. Avoid parentheses within parentheses, or nested parentheses. Correct: (We also administered the Beck Depression Inventory [BDI; Beck, Steer, & Garbin, 1988], but those results are not reported here.)

What do double parentheses mean in Javascript?

It runs the function you just created. The reason to do this is that it encloses all of the code you write within a new scope. This means when you define vars and functions , they will be kept within the scope of that function() you just created.

What does double brackets around word mean?

The brackets enclose text which is not actually part of the quotation but necessary to provide additional context, to allow full understanding.

What does double parentheses mean in Python?

The use of a double parentheses is actually an indicator of one of Python's coolest features - and that is that functions are themselves, objects!


2 Answers

This is a pattern in which the module.exports of the module you are requiring is set to a function. Requiring that module returns a function, and the parentheses after the require evaluates the function with an argument.

In your example above, your ./routes/index.js file would look something like the following:

module.exports = function(app) {   app.get('/', function(req, res) {    });   // ... }; 

This pattern is often used to pass variables to modules, as can bee seen above with the app variable.

like image 136
Tim Cooper Avatar answered Oct 11 '22 19:10

Tim Cooper


Well, require is a function provided by Node.js that basically loads a module for you and it returns whatever you expose in the module that you loaded.

If what you expose (through the use of module.exports) in a given module is a function, then that is what requires returns. For instance.

//moduleX.js module.exports = function(){   return "Helo World"; } 

Then if you require it, you get a function back

var f = require('./moduleX'); console.log(f()); //hello world 

Of course, you could invoke the function directly once you require it.

var greet = require('./moduleX')(); console.log(greet); 
like image 36
Edwin Dalorzo Avatar answered Oct 11 '22 20:10

Edwin Dalorzo