In Express.js why does code after res.json() still execute? In Express.js why does code after res.json() still execute? express express

In Express.js why does code after res.json() still execute?


Express just calls a JavaScript function for the matched route. There's no special magic to know when the function is complete/incomplete. It just runs the function. However, it's very easy to exit the function whenever you want...

You can use return to stop executing the callback for a specific route in express. It's just JavaScript... the function will always attempt to run to completion

app.post('/some/route', (req, res)=> {  if (req.body.var1 >= req.body.var2){    // note the use of `return` here    return res.json({success: false, message: "End time must be AFTER start time"});    // this line will never get called    console.log('Hi')  }  // this code will only happen if the condition above is false  console.log('Hi2')  //other codes});

Warning about string comparsion

You're using

req.body.var1 >= req.body.var2

All HTML form values are sent to the server as strings.

// javascript string comparison"4" > "3"  //=> true"4" > "30" //=> trueparseInt("4", 10) > parseInt("30", 10) //=> false

I'm certain you'll need to make a more educated comparison than that. It looks like they're time values? So you'll likely want to convert those values to Date objects and do an accurate comparison.


Simply return after the res.json function:

res.json({success: false, message: "End time must be AFTER start time"});return; // This will stop anything else from being run


You can return with res.json too.

if (req.body.var1 >= req.body.var2){return res.status(400).json({success: false, message: 'your message'})}