Chetan Motamarri Chetan Motamarri - 1 year ago 61
Node.js Question

When is JavaScript function expression invoked/executed/called in this following code?

var express = require('express')

var app = express();


var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Started server at port", port);

I am beginner in JavaScript. Here in this code, we never called server(); explicitly but it is executing. Also it is not immediately invoked function expression. At what point of time does app.listen() really executed ?

Code obtained from:

Answer Source

the server is not a function. It's a variable. function app.listen(...) is executed right there, on line 7. The result of it is assigned to the variable server.

app.listen() function has a callback method (second parameter). It's executed when app started listening. so to speak. When this callback is called server.address().port will return you server's port.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download