Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 harmony arrow functions in express handlers

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')
})
like image 559
G Sis Avatar asked Apr 18 '16 04:04

G Sis


People also ask

What does => mean in ES6?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

When should you not use arrow functions in ES6?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

What is an ES6 arrow function?

Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular functions. For example, This function // function expression let x = function(x, y) { return x * y; }

Can arrow functions be invoked?

an arrow function is an expr, but we need surrounding parens b/c of "operator precedence" (sorta), so that the final parens to invoke the arrow-IIFE apply to the entire function and not to just the last token of its body.


1 Answers

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.

like image 80
QoP Avatar answered Oct 06 '22 20:10

QoP