Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why wont this if statement work in javascript

I got bored and decided to make a simple API in javascript. big mistake.

For some reason this very simple if/else statement will only run the code in if, instead of else. I have asked my friend who is more experienced in javascript than I am, but he can’t see an issue either.

here is the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.get("/number", (req, res) => {
    const min = req.query.min || 0
    const max = req.query.max || 100

    if (min > max) {
        res.status(400).json({
            error: "min must be less than max. ur actually dumb"
        })
    } else {
        const number = Math.floor(Math.random()*Math.max(min, max)+Math.min(min, max))

        res.json({
            number: number,
            "your ip LEAKED 2021 not clickbait!!!11!1": req.ip
        })
    }
})

here is the output: Image of output

so here I am, asking stack overflow to help me with an if statement. thank you

>Solution :

min and max are strings since they’re passed in as query arguments

You also don’t need Math.min or Math.max since you already know which is bigger/smaller

Also use the ternary operators instead of || since if max is 0, then max will be set to 100

app.get("/number", (req, res) => {
    const min = isNaN(parseInt(req.query.min)) ? 0 : parseInt(req.query.min);
    const max = isNaN(parseInt(req.query.max)) ? 100 : isNaN(parseInt(req.query.max));

    if (min > max) {
        res.status(400).json({
            error: "min must be less than max. ur actually dumb"
        });
    } else {
        const number = Math.floor(Math.random()*max+min);

        res.json({
            number: number,
            "your ip LEAKED 2021 not clickbait!!!11!1": req.ip
        });
    }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading