Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
JavaScript loop ending early after special input?
let num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
while(isNaN(num_cap)) {
    alert("Input must be a number, try again.");
    num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
}
while(num_cap<=1) {
    alert("Number must be greater than 1, try again.");
    num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
}

I am new to programming, specifically javascript. I have written a higher-lower guess game and have resolved just about every issue I’ve come across in the code besides an issue where if my first while loop is triggered and again prompts the user for entry, If I then enter an input that should trigger the second while loop, it still passes through anyways. This problem doesn't happen if I simply begin with entering an input that triggers the second while loop without triggering the first. It only happens if I trigger the first while loop beforehand.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to check for both requirements (number is valid, and also larger than 1) at the same time.

let num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
while(isNaN(num_cap) || num_cap <= 1) {
    alert("Input must be a number larger than 1, try again.");
    num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
}

This is another example that I prefer because it does the parsing in once, in one place, also the validation check is simpler, just num_cap > 1:

let num_cap, isValid;
do {
    num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
    isValid = num_cap > 1;
    if(isValid) { break; }
    alert("Input must be a number larger than 1, try again.");
} while(!isValid);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!