When result.rows is [], how do I test for that?

When result.rows is [], how do I test for that?


So I have a question about when result is []. I am using express, nodejs and postgresql to create an REST QPI. Now, the question that I have is. When result.rows is [], does that mean that is null? I tried doing “if(result == null)”, but that didn’t seem to work either. Thanks for the help!

client.query("select waiter_id from students", function(err, result){
        res.json({success: false, msg: "error"});
Problem courtesy of: user3192435


It’s an empty array, so you have to check the length property

if (result.length === 0)


if (!result.length)     

sometimes it can be useful to check that an array was returned first to avoid errors

if (Array.isArray(result ) && result.length) {
     // It's an array, and it has content
} else {
     // It's either not an array at all, or it's empty
Solution courtesy of: adeneo


Leave a Reply

Your email address will not be published. Required fields are marked *