Chetan Motamarri Chetan Motamarri - 4 months ago 8x
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:


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.