Chetan Motamarri Chetan Motamarri - 5 months ago 10
Node.js Question

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

var express = require('express')

var app = express();

app.use(express.static('static'));

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: https://github.com/vasansr/react-tutorial-mern/blob/master/webapp.js

Answer

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.