9.6.4. Beyond for Loops // Input Validation // while loops

const input = require('readline-sync');

let num = input.question('Please enter a positive number:');
num = Number(num);

while (num <= 0) {
   num = input.question('Invalid input. Please enter a positive number:');
   num = Number(num);
}

/*This program is an example of input validation. It prompts the user to 
enter a positive number, converting the input string to the number data
type. If the number is not positive, then the user is prompted again 
within the body of the loop. As long as the user continues to input 
non-positive numbers, the loop will continue to iterate.

This example illustrates the additional flexibility provided by while 
loops. While we use for loops to iterate over fixed collections 
(a string, an array, a collection of integers), the while loop can 
be used to iterate in more general circumstances. For the input 
validation example, at runtime it cannot be determined how many times
the loop will repeat.*/

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source