softshipper
softshipper

Reputation: 34099

express route return necessary or not

I am using the express framework for my web app. I picked-up some code from a book, look at this code, this a route to a page:

app.post('/register', function(req, res) {
  var firstName = req.param('firstName', '');
  var lastName = req.param('lastName', '');
  var email = req.param('email', null);
  var password = req.param('password', null);

  if ( null == email || email.length < 1
       || null == password || password.length < 1 ) {
    res.send(400);
    return;
  }

What is the purpose of the return here, is it necessary?

Upvotes: 22

Views: 8218

Answers (2)

cybng
cybng

Reputation: 1

res.render("view page name",{title:"",data:""});

Upvotes: -3

Peter Lyons
Peter Lyons

Reputation: 146124

The return is only necessary if you have more code below that point in the route handler function and you want to bypass the rest of the function. Nothing in express will look at or care about the value you return. If you are at the bottom of your function anyway, you may omit the return statement entirely.

Typically, you see patterns like:

  • first do some prerequisite checking, validation, authorization, or similar logic
  • If any of that fails, send and error and return from the function to bypass the main logic. These are called guard clauses.
  • Main logic code comes next and only executes if the return wasn't encountered.

Upvotes: 36

Related Questions