Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS, Is it a bad practise to return res.json

I'm building a ExpressJS application with NodeJS. My question is there any performance difference if I do

app.get('/test', function(req, res) {
    fn(function(err, data) {
        if (err) {
            return res.json(400, {
                error: 1,
                msg: "some error"
            });
        }

        ///more code
    });
});

instead of

app.get('/test', function(req, res) {
    fn(function(err, data) {
        if (err) {
            res.json(400, {
                error: 1,
                msg: "some error"
            });
            return;
        }

        ///more code
    });
});

Do returning the res variable make any addition load on the server. Both codes work, just the first looks better to me and I save 1 line.

like image 862
Deepsy Avatar asked Apr 07 '14 01:04

Deepsy


1 Answers

On the contrary, I think many would tell you this sort of idiom is a very sound practice as it makes clear to the reader (often your future self) that you are exiting). What is very nice about the strategy in this particular case is that you can save a bit more code since you now only have a single statement in your conditional branch, which means you can lose some curly braces.

app.get('/test', function(req, res) {
    fn(function(err, data) {
        if (err)  return res.json(400, {
                    error: 1,
                    msg: "some error"
                 });
    ///more code
    });
});

But you asked if there was a performance difference. If there is, I think it would be all but imperceptible.

like image 191
barry-johnson Avatar answered Oct 06 '22 07:10

barry-johnson