Here's a JavaScript program that fulfills your requirements. It prompts the user for a number greater than 0 and then countdowns to "BLASTOFF!".
// Function to get a valid number greater than 0 from the user
function promptNum(message) {
let num;
do {
num = parseInt(prompt(message), 10);
} while (isNaN(num) || num <= 0); // Keep prompting until a valid number is given
return num;
}
// Create and assign variable based on user input
var counter = promptNum("Enter a number greater than 0:");
// Update the conditional statement so that the loop runs
while (counter > 0) {
// Print the number in the countdown
console.log(counter);
// Decrease the value of the counter by 1 each time
counter--;
}
// Print "BLASTOFF!" after the loop is done running
console.log("BLASTOFF!");
How the Code Works:
-
The
promptNum
function ensures that the user inputs a valid number greater than 0. If the user enters an invalid input (either a non-number or a number less than or equal to 0), they will be prompted again until a valid number is entered. -
The variable
counter
is assigned the valid number from the user. -
The
while
loop checks ifcounter
is greater than 0. Inside the loop:- The current value of
counter
is printed to the console. - The value of
counter
is then decreased by 1.
- The current value of
-
Once the loop finishes, "BLASTOFF!" is printed to the console.
You can run this code in any JavaScript environment (like a web browser’s console) to see it in action!