In Node.js
I see sometimes a declaration like this:
var App = require('express')();
What do the empty brackets '()'
at the end mean?
I am suspecting the declaration above is equivalent to something like:
var Express = require('express');
var App = Express();
Is that right?
In Node.js
I see sometimes a declaration like this:
var App = require('express')();
What do the empty brackets '()'
at the end mean?
I am suspecting the declaration above is equivalent to something like:
var Express = require('express');
var App = Express();
Is that right?
Share edited May 20, 2016 at 16:27 user663031 asked May 20, 2016 at 15:57 eYeeYe 1,7332 gold badges29 silver badges60 bronze badges 3-
You are correct. Require returns a function which is called using the
()
. – Tejas Kale Commented May 20, 2016 at 15:59 - 1 Also check out this blog post : fredkschott./post/2014/06/require-and-the-module-system – Tejas Kale Commented May 20, 2016 at 16:01
-
Syntactically, by definition, the
()
could do only thing, which is to invoke a function. – user663031 Commented May 20, 2016 at 16:28
2 Answers
Reset to default 8As James already answered the module returns a function which is than invoked in this manner.
Here a simple code sample to make it easier understandable.
function a() {
function b() {
alert('Alert me!');
}
return b;
}
a()();
//alerts 'Alert me!'
Essentially the express
module is returning a function. The empty brackets call the function so now App
is the result of the returned function
.