TLP
TLP

Reputation: 109

Use query input for if statement condition

I am doing a mini-API on Express.

On an request, I want to verify that all the query parameters are filled.

Hence, my intuition led me to this:

app.get("/book", (req, res) => {

    console.log(req.query.seats, req.query.category, req.query.date);

    let isEmpty =
        req.query.seats === undefined ||
        req.query.category === undefined ||
        req.query.date === undefined;

    console.log(isEmpty);

    if (isEmpty === true) {
        console.log("here3");
        res.status(400).send("Missing input");
    }

    // else continue with instructions
}

Nevertheless, the console outputs false for isEmpty, while it tells that elements (req.query.category) is undefined, passing to the next instruction and not catching the error.

Does the elements have a different behavior in a console log and and comparison ?

thanks !

Upvotes: 0

Views: 1010

Answers (1)

Flo
Flo

Reputation: 986

If you want to check for undefined AND empty string without problem you could do this way :

let isEmpty = !req.query.seats || !req.query.category || !req.query.date

For example :

var seats = '';
var category = undefined;
var date = '';


let isEmpty = !seats || !category || !date
console.log(isEmpty) // true

Upvotes: 1

Related Questions