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

The button effortlessly transforms into a sleek email submission form

I have a button that is already styled with basic CSS properties for active and hover states. I would like to add functionality so that when the "Join the Loop" button is clicked, it transforms into a simple email form similar to the one found at Apologie ...

Modifying the property value in a child component using the parent component in VueJS

Hey there, I'm facing an issue where I need to update a prop in my child component when the parent component changes the value. However, I'm attempting to do this in a unique way and running into a problem where the child prop is not being update ...

Extracting JavaScript variable data to PHP using Ajax technology

I've been trying to save latitude and longitude values in PHP variables, but I'm having trouble. Here is the code I'm using. Can anyone please help me figure out why these values are not being stored in PHP variables: Code: <!DOCTYPE h ...

Copy the contents of matrixA into matrixB and append a new element to each array within matrixB

I want to copy the values from matrixA into matrixB and then add a new element to each array in matrixB. let number = 100; matrixA = [ [1, 2], [3, 4] ]; matrixB = [ [1, 2, 100], [3, 4, 100] ]; Currently, my code looks like this: for (let ...

When attempting to reference a custom module within a React application, the error message "moment is not a function" may appear

I am facing an issue while trying to integrate a custom module I developed into a basic React application using react-boilerplate. Upon importing the module, I encountered an error stating that the moment function within the module is undefined. Here is t ...

Is it possible to create a table using a loop in an SQLite query?

Welcome In the company where I work, Excel is currently being used to manage a large database of items for cost estimation purposes. To simplify this process, I am developing an Electron App that will replace Excel with a more user-friendly interface and ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

Step-by-step guide on integrating a specific location into Google Maps using React.js

I'm in the process of revamping my website using Reactjs. I want to incorporate a specific Google location with reviews on the map, similar to how it appears on this example (My current website is built on Wordpress). As of now, all I've been ab ...

Removing a faded out div with Vanilla JavaScript

I am struggling with a JS transition issue. My goal is to have the div automatically removed once it reaches opacity 0. However, currently I need to move my mouse out of the div area for it to be removed. This is because of a mouseleave event listener that ...

How can I turn off Angular Grid's virtualization feature, where Angular generates div elements for the grid based on height and width positions?

Currently, I am working with an Angular grid (ag-grid) that dynamically creates div elements in the DOM to display data as the user scrolls or views different sections. As part of my testing process using Selenium WebDriver, I need to retrieve this data fr ...

How come the behavior of Array.prototype.push() results in creating an endlessly nested array when used on itself?

While testing out the following code: const animals = ['pigs', 'goats', 'sheep']; animals.push(animals) console.log(animals); An error occurred in my testing environment: Issue: Maximum call stack size exceeded. What is c ...

Start the Vue component only after ensuring that the element has been fully loaded

I have created a small vue.js component in JavaScript. Is there an elegant way to instantiate the vue component only when the element is loaded? The problem I am facing is that I'm receiving warnings in other HTML files where the element does not ex ...

The Angular $rootScope.user.userMessage throws an error stating that it is not an object

I am encountering an issue: Error: The object '$rootScope.user.userMessage' is not defined. (evaluating 'typeof $rootScope.user.userMessage') This error arises from the following code snippet: if (typeof($rootScope.user.userMessage ...

sending data from a servlet to ajax

Implementing a star-based voting system involves sending an ajax request to update the database through a servlet when a user casts their vote. This is the ajax code used: $.ajax({ type:'GET', contentType: "charset=utf- ...

When transitioning between steps in Material UI React, the Vertical Stepper component should automatically scroll to the top of

When switching steps in Material UI's vertical stepper, it should automatically scroll to the beginning of the selected step. One potential solution is to utilize a ref to scroll to the stepper titles. More information on scrolling to specific elemen ...

Top Method for Initiating AJAX Request on WebForms Page

Looking for the best way to execute an AJAX call in a WebForms application? While ASP.NET AJAX components are an option, some may find them a bit heavy compared to the cleaner approach in MVC. Page Methods can be used, but they require static methods ...

The concept of asynchronicity and callbacks in JavaScript

As a newcomer to the world of JavaScript and Stack Overflow, I have been learning about synchronous, asynchronous, and callbacks through various videos and blogs. However, I still have a lingering doubt. If synchronous code means following a sequential ord ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

In just a single line of code, you can iterate through a Record object and retrieve an array of DOM elements

I am working with an object type MyType = 'name' | 'base' | 'six'; obj: MyType = { 'name': {key: 'm1'}, 'base': {key: 'm2'}, 'six': {key: 'm3'}, } My goal is ...

Mongoose encountering issue with non-essential Geo spatial field

Utilizing the Mongoose Schema, a simplified version is shown below: const customSchema = new mongoose.Schema({ title:{ type: String, required: true }, position:{ type: { type: String, default: 'Location', enum ...