CreateServer method question

First of all, apologies for the simplicity of this question.

I am at the beginning of the chapter looking at the code below.

I have been sitting here trying to figure this code out for half an hour and I cannot figure it out, so I would appreciate if someone could explain it to me. I understand that createServer() takes in a function as a parameter, and that we are instantiating that function as we go (an anonymous function). However, what I don’t understand are the parameters for this anonymous function. It takes in the parameters ‘req’ and ‘res’. We haven’t defined these variables before, and these are some of the first lines that our code runs at all. So what can possibly be stored in these variables, and how did those values get there?

My programming background is object oriented in Java and C++ and I’m taking my first plunge into web development and Javascript is very unintuitve to me.


Hi @travpav84, no worries! The function oriented paradigm is a big shift, esp. in an industry dominated by OOP :slight_smile:

req and res are called function “parameters”: you can name them whatever you want, and they will hold the arguments that the function is invoked with. You could imagine that .createServer() does something like this:

http.createServer = function(responder) {
  /* `responder` is the anonymous function you passed in to `.createServer`

  /* do networking... */
  /* on incoming connection, create a Response and Request object: */
  var request = /* ... */
  var response = /* ... */

  /* invoke your anonymous function with two arguments */
  responder(request, response);

http.createServer() takes your anonymous function and invokes it, passing in two arguments (a request and response object it constructed). So req and res in your function are arbitrary “placeholders” that will receive the first and second argument.

How do you know what arguments will be passed in, and how did we know that we should pass in a function with two parameters? In this case, that’s from reading the Node stdlib docs.

Hope that helps! If you’re interested in delving more into the functional programming perspective, I highly recommend a free read called JavaScript Allonge.