14

I am learning Nodejs and I do not fully understand the returns. For example, next() in many cases is suggested to be returned in order to make sure execution stop after triggering it (Reference). However, for cases like simple response, is return needed, what is the difference and what is preferred:

res.json({ message: 'Invalid access token' });

vs.

return res.json({ message: 'Invalid access token' });
Community
  • 1
  • 1
eYe
  • 1,695
  • 2
  • 29
  • 54

1 Answers1

15

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.

Chris Malherbe
  • 238
  • 2
  • 9
  • http://stackoverflow.com/questions/16810449/when-to-use-next-and-return-next-in-node-js?lq=1 – Chris Malherbe Jun 09 '16 at 13:19
  • Thank you. So technically if I am careful enough I do not have to return when early return is not required? – eYe Jun 09 '16 at 13:22
  • 2
    Yes, technically you don`t have to, I try to always return when calling a callback. It just eliminates a lot of debugging time always returning this though. Calling the callbacks more than once it ends in tears. :( – Chris Malherbe Jun 09 '16 at 13:27
  • But why is this the case? If res is sent back to the client, that means, technically, that the HTTP req + res cycle is done and execution is finished. Why isn't res.json() a function terminator on its own. – aelmosalamy Jul 11 '20 at 23:48
  • @aelmosalamy Technically yes, but we might have interceptors or post-processors. If you are from java world, think about aspect oriented programming etc. So even if response is done, server might want to do some post processing logic like logging or clearing some cache or something. for that reason I think res.json() is not a function terminator on its own. – theprogrammer Sep 01 '20 at 23:51