What could be causing this JavaScript if statement to malfunction?

I found myself with some free time and decided to create a basic API using JavaScript. What I thought would be simple turned into a frustrating mistake.

Oddly enough, my if/else statement isn't working correctly - it only executes the code within the if block. Even after consulting a friend who is more experienced in JavaScript, we couldn't pinpoint the issue.

Here's the snippet of code:

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. Seriously?"
        })
    } 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
        })
    }
})

And here's what it outputs:

Left scratching my head over this if statement malfunction, I turn to Stack Overflow for assistance. Your help is appreciated!

Answer №1

min and max are treated as strings since they are provided as query parameters

You can handle the comparison of min and max without using Math.min or Math.max as their relationship is known

Additionally, consider utilizing ternary operators instead of || to set a default value for max if it is equal to 0

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 : parseInt(req.query.max);

    if (min > max) {
        res.status(400).json({
            error: "The minimum value must be less than the maximum value."
        });
    } else {
        const number = Math.floor(Math.random()*max+min);

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

Answer №2

Make sure to convert req.query.min and req.query.max into integers first otherwise, the comparison won't behave as expected

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

  if (minNumber > maxNumber) {
    res.status(400).json({
        error: "Minimum value must be less than maximum value. You made a mistake."
    });
  } else {
    const generatedNumber = Math.floor(Math.random()*maxNumber+minNumber);

    res.json({
        number: generatedNumber,
        "Your IP Exposed 2021 not clickbait!!!11!1": req.ip
    });
  }
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on displaying a loading spinner during the retrieval and assembly of a component framework (Astro Island) with Vue and AstroJS

Here is the astro code I'm working on: --- import BaseLayout from '../../layouts/BaseLayout.astro'; import ListadoProfesionales from "../../components/pages/ListadoProfesionales/ListadoProfesionales.vue"; --- <BaseLayout title= ...

The Vue.js scripts and styles declared in the index.html file seem to be malfunctioning

I acquired a theme that includes html, css3, and js files, and I included the file path as shown below: <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Porto - Responsive HTML5 Te ...

Does adding the Angular bootstrap script at the end of the body tag impact webpage speed more than using ng-app on the body tag?

In the past, we had placed ng-app on the body tag which led to problems with dependency injection when multiple modules were being used on the same webpage. This required module creators to be aware of the existing app and inject their app into it. We are ...

Troubleshooting NPM installation failures with SQLite build

After updating to macOS Mojave and installing the latest versions of node 12.1.0, npm 6.9.0, brew 2.1.1, and Python 2.7.10 on darwin, I encountered an issue while running npm install in a package.json file for a project that includes "sqlite3": "4.0.6". ...

Generating an interactive Datepicker using Jquery

How can I design a dynamic date picker similar to the image provided below? I have attempted to create one, but I am looking for a more interactive date picker. Is there a way to achieve the design shown in the image? The current date picker does not meet ...

Enhance Bootstrap modals by automatically adjusting the background shadow mask when resizing or changing the content within the modal window

Incorporated within my bootstrap modal window is a form alongside a link that triggers the jQuery functionality of .slideToggle(). By interacting with this link, a concealed div expands. Consequently, the size of the modal popover becomes fluid. Upon click ...

Assign an identifier to the HTML helper Html.EditorFor

When using a textbox created with the HTML helper "@Html.EditorFor", there may be a need to perform some action with JavaScript on its change event. In order to do this, an ID needs to be set for the textbox. For example, if you need to set a string value ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

Show nested arrays in Vue.js exhibition

As a newcomer to vue, I've been navigating my way around with some success. Lately, I've been dealing with JSON data structured like this: [ { "name": "jack", "age": "twenty", "Colors&qu ...

JavaScript callbacks are not executed synchronously

My Objective : I am attempting to initiate a payment order in the payment gateway server and then send back the order details to the client using Firebase cloud functions. This process involves utilizing firebase cloud functions. The Order() function ha ...

Is it feasible to add on to an existing object in the database? (Using Node.js and Mongoose

After saving an object to the database using the following code: var newObject = new PObject({ value : 'before', id : 123456 }); newObject.save(function(err) { if (err) ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

What is the proper way to retrieve multiple property values stored in a property name using getJSON

I'm having trouble getting multiple languages to work in my code. Could someone assist me and provide guidance on how to write multiple choices for the property name language? When I input code like this to display only Dota 2 games in English, every ...

The identical items combined into a single array

I have a specific data structure that I am struggling to manipulate in JavaScript. The goal is to merge objects with the same invoice_nr into one array, while keeping other objects in separate arrays. const result = [ { invoice_nr: 16, order_id: ...

Tips for styling buttons in react-admin with custom CSS

I need some help with customizing buttons in react-admin. I am new to the platform and unsure about how to go about changing the button CSS for various actions such as create, edit, and export. Can anyone provide guidance on the best way to customize these ...

Using the highcharts-ng library in combination with ng-repeat was successful in creating multiple charts. However, in order to display different data for each chart, the

I need to provide the date either from the view template or possibly from the controller in order for the highchart to display the data specified by the <highchart /> directive. Explanation : <ul> <li ng-repeat="li in list"> ...

Tips for creating dynamic row styles in a fluid table layout?

Could someone help me figure this out? I'm not familiar with JavaScript and need assistance as I've never created it, only edited existing scripts. I have a layout with two tables side-by-side. On mobile devices, the second table is pushed below ...

Having issues when dynamically adding options to a multiselect dropdown

I'm working on dynamically adding options to a multiselect using AJAX: <select size='2' name="CraftCode" id=@ccrf class="form-control js-select manualentrydd" ></select> $.ajax({ type: "GET", url: "GetCraftCodes", data: ...

Concealing and revealing template URLs with AngularJS

I am currently working with a dynamic Array in my Controller that contains templates (html files) structured similarly to the example below: $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: ...

D3 Treemap for handling extensive sets of data

I am uncertain if there exists a method to incorporate the desired feature. I am seeking a solution similar to zoomable treemaps, but to initially load a limited number of child levels and then dynamically add more child nodes without requiring a node clic ...