0

For exmaple, I write the following code:

var http = require('http');

var server = http.createServer(function(req, res) {
  res.end('Hello world!');
});

server.listen(8000, function() {
  console.log('Serever started');
});
  

However, the definition of server.listen() is like this:

server.listen(port, hostname, backlog, callback);

listen() method has four parameters while only two parameters port and callback were passed in my code. How the method knows that function(){console.log('Server started');} is 'callback' and not 'hostname?' Does it automatically check the type of parameters?

user3698042
  • 485
  • 1
  • 4
  • 7
  • 1
    Node.js doesn't, the function does. – Quentin Nov 07 '18 at 13:21
  • The `listen` function itself recognizes parameters types, and overloading itself, so in your example `port` is a number, `hostname` probably string, `backlog` probably string too, and the `callback` is a function. Then in function body there is logic which decides which parameter represents what. Thats actually the power of dynamicly typed languages – bladekp Nov 07 '18 at 13:28
  • In example you provided second parameter is function, so `listen` suspects thats this is not `hostname` or `backlog`, but a `callback`, and uses it as a `callback`. In staticly typed languades, like Java, `listen` function developer, would be forced to overload that method several times. So in javascript this method is defined once, in java it would be defined like five or more times, each definition with different parameters list – bladekp Nov 07 '18 at 13:36

0 Answers0