Home > Blockchain >  Why does the || operator not work in JavaScript?
Why does the || operator not work in JavaScript?

Time:11-27

I am trying to paginate using Node.js and Express and I want if the slug <= 0, slug = 1.

new(req, res, next) {
        let perPage = 16;
        //let page = req.params.page <= 0 ? 1: req.params.page; //This work
        let page = req.params.page || 1; //BUT this NOT work, please explain for me

        Product 
            .find()
            .skip((perPage * (page - 1)))
            .limit(perPage)
            .exec((err, products) => {
                    Product.countDocuments((err, count) => { 
                        if (err) return next(err);
                        res.render('product/index_product', {
                            products, 
                            current: page, 
                            pages: Math.ceil(count / perPage) 
                        });
                    });
            });
    }

I used the || operator to solve it but it does not work, I don't know why.

CodePudding user response:

In the case of the page being 0, query string parameters are parsed as strings.

req.params.page <= 0 ? 1 works because '0' is, lexiographically, indeed <= 0 (when then 0 on the right gets implicitly coerced to '0').

console.log('0' <= 0);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

But '0' is not falsey, so

let page = req.params.page || 1;

is

let page = '0' || 1;
let page = '0'

Convert the page to a number first.

const paramPage = Number(req.params.page);
const page = paramPage || 1;

In the case of the page being negative, let page = req.params.page || 1 wouldn't make sense anyway - negative numbers are truthy too. If that's a possibility in your code, your original approach of

const page = req.params.page <= 0 ? 1:

is the best one there is.

  • Related