ShankarGuru
ShankarGuru

Reputation: 625

function ()() in javascript

I am not sure how to call/frame this question title, but can anyone explain me what does the below code do?

var routes = require("./routes/routes.js")(app);

I am seeing a second () with app being passed, what does that do? https://github.com/couchbaselabs/restful-angularjs-nodejs/blob/master/app.js

To my surprise, in the code above the variable routes is not at all used in app.js? what's the purpose. I am quite confused here does (app) argument do anything magic here?

Upvotes: 5

Views: 66

Answers (1)

nwellnhof
nwellnhof

Reputation: 33618

The construct

foo()();

expects that foo() returns a function and calls it immediately. It's equivalent to the more readable:

var func = foo();
func();

A similar construct you'll often see is:

(function() {
    // function definition
})(args);

This defines a function and calls it immediately. The primary use is to emulate block scope for variables.

Upvotes: 6

Related Questions