Tips on obtaining user input through prompt for verifying if a number within a while loop

I am a beginner at javascript and I have been searching everywhere for an answer on how to validate user input from a prompt to ensure the correct number is entered. I've tried result!==isNan(), result==isNan(Nan), and various other variations. Can someone please explain why this isn't working and provide guidance on how to make it work?


var result = prompt("Enter a number between 4-10"); 
    while (result<4 || result>10 || result==isNaN(result)) {
        var result = prompt("Please enter a number between 4-10!");
    }
  alert ("Success")

Answer №1

To determine if the result is valid, you can use the following code: isNan(result) == true

<script>
var result = prompt("Please enter a number between 4 and 10"); 
while (result < 4 || result > 10 || isNaN(result) == true) {
    var result = prompt("You must enter a number between 4 and 10!");
}
alert ("Success")
</script>

Answer №2

The code result==isNaN(result) is not being executed at all

// When using prompt, values returned are strings or null (if cancelled)
// Comparing with a number will convert values to numbers automatically
console.log(Number(null)) // 0
console.log(Number('5')) // 5
console.log(Number('')) // 0

// Due to the condition result<4 || result>10 evaluating to true for null and '', isNaN() code is never reached, leading to an endless loop.

var result = prompt("Enter a number between 4-10"); 
while (result<4 || result>10) {
  result = prompt("Please enter a number between 4-10!");
  if (result === null) break;
}
alert(`Success: ${result}`)

Consider using recursion in place of the while loop

askUser();

function askUser(){
  let answer = prompt('Hello! Please input a number between 4 and 10:');
  if (answer > 4 && answer < 10)
    alert('Thank you, you're awesome!')
  else if (answer === null)
    alert('Seriously? You can't think of a number between 4 and 10??!?!?')
  else 
    askUserAgain();
}

function askUserAgain() {
  let answer = prompt('The entered value is not between 4 and 10, try again.');
  if (answer > 4 && answer < 10)
    alert('Thank you, you're awesome!')
  else if (answer === null)
    alert('Seriously? You can't think of a number between 4 and 10??!?!?')
  else 
    askUserAgain();
}

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 guide on adding two fields together in AngularJS and displaying the output in a label

I am facing a unique issue on my webpage. Including two inputs and a label in the page, I want the label to display the sum of the values entered into these two inputs. My initial attempt was as follows: Sub-Total <input type="text" ng-model="Propert ...

Validating image dimensions with the data-parsley plugin

Is there a way to validate image dimensions with data-parsley? I attempted the code below, but it is not working. data-parsley-dimensions-options='{ "min_width": "100", "max_width": "100", "m ...

Importing three.js using ES6 syntax

When it comes to working with ES6, my workflow involves using Babel and babel-plugin-transform-es2015-modules-system.js specifically to transform module import/export for compatibility with system.js. I rely on a "green" browser for most ES6 features excep ...

Is there a way to refresh the page in NextJs whenever the parameters are modified without the need for reloading?

Currently, I am navigating on http://localhost:3000/?groupId=chicago&dayOfWeek=tuesday. Despite pressing a button on a component, the desired outcome of transitioning to another day, like Thursday, is not occurring. import { useRouter, usePathname, use ...

Is there a way to set the y-axis camera rotation in threejs to 360 degrees?

I am trying to create a 360 viewer for a specific product using a 3D object. The goal is to rotate the camera around the object at a 45-degree angle per click in the correct direction. However, I am facing difficulties with this task. Camera: this.camera ...

Form data triggering inaccurate results in ajax response

After following online tutorials and seeking help from Stack Overflow, I am still struggling with a strange issue related to AJAX. I appreciate any assistance in solving this problem. I am trying to create a feature where users can search for match result ...

What is the best way to calculate the average grade for each student in an array that contains objects with exam submission data?

Imagine having a collection of objects that hold details about exams submitted over a period. Here is the structure: [ { name: 'Freddy', grade: 10, date: '20/07/2022' }, { name: 'Jose', grade: 8, date:'20/07/2022& ...

PointerLockControls maintains a constant speed without slowing down (threejs)

I have integrated THREE.PointerLockControls into my project following the implementation demonstrated in this example (view code). The code seems to be accurately translated from the example, but I am facing issues with deceleration of the controller once ...

Do I need to include a callback in my AWS Lambda handler function?

What is the function of the callback in the lambda handler? It appears to be utilizing the sns variable and I am looking to make some modifications to the variables. exports.handler = function(event, context, callback) { console.log("AWS lambda and ...

Can you explain the contrast between body.onunload and body.onbeforeunload?

Similar Question: Explaining the distinction between onbeforeunload and onunload Tell me, what sets apart body.onunload from body.onbeforeunload events? From what I've gathered, I should be able to apply onunload and onbeforeunload to any HTML el ...

Leveraging Selenium for testing Polymer components and shadow DOM structures

Having trouble using Selenium with elements inside a shadow DOM. Is there a specific method to handle this situation? Any guidance on what I might be doing wrong? Here are the various approaches I've attempted: var webdriver = require('selenium ...

Utilize the Discord API to send a direct message to a specific user by their unique ID

Recently, I've been exploring ways to utilize Discord's API in order to send a private message to a specific user based on their user ID. I understand that there are libraries like Discord.JS and Discord.py that allow for this functionality, how ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

Using React to showcase a base64 image representation

I'm struggling to show an image that has been sent from my Node/Express server to my React application. I've tried looking at solutions on other platforms, but so far nothing has worked for me. Let me outline the steps I have taken: The image is ...

"Revamp your Node.js and HTML with the click of a

I recently built a basic counter for my website, but I'm having trouble with its consistency across different browsers and computers. The button seems to work only about 1/12th of the time. Any tips on making it more reliable? Any help would be great ...

Generate a structured table display using the JSON information

How can I convert the following JSON data into a tabular view? {"data_report":[{"data":[1,2,0,3],"label":"Test1","backgroundColor":"blue"}, {"data":[3,4,2,5],"label":"test2","backgroundColor":"#a3eaae"}, {"data":[2,3,1,4],"label":" ...

What causes the text field and checkbox to move downward as I enter text?

I'm currently working on a mock login page using React and Material UI. I implemented a feature where the show/hide password icon only appears when the user starts typing in the password field. However, after making this change, I noticed that the pas ...

Issue: Missing authentication code (Mongoose-encryption)

Encountering an error when trying to login a registered user. The error appeared after implementing the dotenv package to secure my database encryption key. Fortunately, proccess.env.SECRET is functioning correctly. Identified the potential issue here: ...

Create a table dynamically in the code-behind of an ASP.NET page and then retrieve it using JavaScript with getElementById

When a table is created and added dynamically, the ClientID property in the code behind may not reflect the actual ID of the element in the file, causing issues with document.getElementById functionality. Is there a way to add a control so that it can be ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...