Where do the parameters in a javascript callback function come from?

They come from the same place they come from when a normal non callback function is invoked, at invocation time.

If you have this function,

function add (a, b) {
  return a + b
}

You’re fine with knowing that a and b come from when you invoke add,

add(1,2)

and it’s the same principle with callbacks, don’t let your brain get all twisted just because it’s getting invoked later.

At some point the function you pass to router.get is going to be invoked, and when it does, it will receive req and res.

Let’s pretend the definition for router.get looks like this

router.get = function(endpoint, cb){
   //do something
   var request = {}
   var response = {}
   cb(request, response) // invocation time
}

In the case of your example, it’s just up to node to pass your function request and response whenever .get is invoked.

Leave a Comment