20

Is there a reason not to use arrows instead of regular function expressions in expressjs for handlers in middleware?

app.use(mountSomething())
router.use(mountSomethingElse())

app.get('/', (req,res,next)=> { 
    next();
})

route.get('/path', (req,res,next)=>{
    res.send('send')
})
Mulan
  • 129,518
  • 31
  • 228
  • 259
G Sis
  • 199
  • 2
  • 7
  • 2
    What makes you think that you shouldn't use arrow functions instead of regular functions? – Saad Apr 18 '16 at 04:13
  • @saadq I've edited the question – G Sis Apr 18 '16 at 04:16
  • The only difference between a regular function expression and an arrow function is that the arrow function doesn't bind its own `this` value (You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)). So in a case like this where you won't need to use `this`, using an arrow function would be fine. – Saad Apr 18 '16 at 04:37
  • 1
    If you not using generators inside handlers, you can totally use fat arrows. – Swaraj Giri Apr 18 '16 at 06:23
  • 1
    [No](http://stackoverflow.com/q/34361379/1048572) – Bergi Apr 18 '16 at 08:18

1 Answers1

18
app.get('/', (req,res,next)=> { 
    next();
})

is the same as

app.get('/', function(req,res,next) { 
        next();
}.bind(this))

In most cases you are not going to use 'this'(which will be probably undefined) in the handlers, so you are free to use arrow functions.

Mulan
  • 129,518
  • 31
  • 228
  • 259
QoP
  • 27,388
  • 16
  • 74
  • 74