How to get the number of parameters on a provided function?

Express.js uses error-handling middleware like this:

app.use(function(err, req, res, next) {...})

which only gets called when an error happens in one of the previous middlewares.

I've verified with the following code:

app.use(function(err, req, res, next){
    console.log("CALL BAD");
    res.send(500, 'Internal server error');
});

app.use(function(req, res, next){
    console.log("CALL GOOD");
    next();
});

That the first function is only called when there's an error, but if everything is ok, express skips it. So it must somehow distinguish function with 4 args from the one with 3 args? How does it do that?

E.g. I know about the arguments magic variable, etc. But in this case express does something like function addroute(fn) {if (has4Params(fn)) doThis(); }

I assume they're using the Function.length property, which is the number of arguments expected by a function. So something like (badly coded for the sake of brevity):

var myFunction = function(callback) {
   if(callback.length == 3) {
       console.log("CALL BAD");
       return;
   }
   if(callback.length == 4) {
       console.log("CALL GOOD");
       return;
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length for more details.