Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 654
ShankarGuru Avatar asked Dec 05 '15 09:12

ShankarGuru


People also ask

What is a function in JavaScript?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.

What is function in JavaScript with example?

A function is declared using the function keyword. The basic rules of naming a function are similar to naming a variable. It is better to write a descriptive name for your function. For example, if a function is used to add two numbers, you could name the function add or addNumbers .


1 Answers

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.

like image 103
nwellnhof Avatar answered Oct 04 '22 15:10

nwellnhof