Express: Can I use "new" on express.Router?

Created on 4 Aug 2020  路  1Comment  路  Source: expressjs/express

eslint is complaining with the initialization of a router as per documentation.

const routes = require('express').Router();
// 1:35  error  A function with a name starting with an uppercase letter should only be used as a constructor  new-cap

And as I searched for whether it is possible to call express.Router with new, I come across a few instances of this usage:

So, is it recommended to use/not use new when creating a Router? I know that it doesn't make any difference for any function that returns any object, but I don't know enough to make the call whether there is any potential drawback. As far as I can tell, this behavior is undocumented, except by inference from knowledge on the new operator.

question

Most helpful comment

Hi @chtseac ! Our Router is a JavaScript constructor, and as such, you should use the new keyword with it. This is the same as the Error object, for example. But, just like the Error object, you don't _have to_ use the new keyword, but if you don't, internally it is just called again with the new keyword, so best practice is always to use the new keyword when using a constructor (like Router or Error).

I hope this helps!

>All comments

Hi @chtseac ! Our Router is a JavaScript constructor, and as such, you should use the new keyword with it. This is the same as the Error object, for example. But, just like the Error object, you don't _have to_ use the new keyword, but if you don't, internally it is just called again with the new keyword, so best practice is always to use the new keyword when using a constructor (like Router or Error).

I hope this helps!

Was this page helpful?
0 / 5 - 0 ratings