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?
New code examples in category Javascript
-
Javascript 2023-04-21 22:52:36
-
Javascript 2022-03-27 22:25:20 javascript download string as file
-
Javascript 2022-03-27 21:40:22 sort numbers in array javascript
-
Javascript 2022-03-27 21:20:04 compare two arrays and return the difference javascript
-
Javascript 2022-03-27 21:15:02 javascript regex french phone number
-
Javascript 2022-03-27 21:05:03 cypress custom error message
-
Javascript 2022-03-27 21:00:05 create element javascript with id
-
Javascript 2022-03-27 20:40:57 feather icons react
-
Javascript 2022-03-27 20:20:01 how to make graphql request in axios
-
Javascript 2022-03-27 20:15:07 bootstrap validator password and confirm password