The return is used to stop execution. It is often used to do some form of early return based on a condition.
Forgetting the return often leads to the function continuing execution instead of returning. The examples are typical express middle-ware examples.
If the middle-ware function looks like this:
function doSomething(req, res, next){
return res.json({ message: 'Invalid access token' });
}
The resultant behavior would be exactly the same as:
function doSomething(req, res, next){
res.json({ message: 'Invalid access token' });
}
But very often this pattern is implemented:
function doSomething(req, res, next){
if(token.isValid){
return res.json({ message: 'Invalid access token' }); // return is very important here
}
next();
}
As you can see here when the return is ommited and the token is invlaid, the function will call the res.json() method but then continue on to the next() method which is not the intended behaviour.