Canceled
// or: OK but empty
// or: Entered: hello
How It Works
Call prompt. No default this time.
null first. Cancel is not the same as blank.
Empty string. User pressed OK with no text.
Else branch. Real input to use.
Example 3 — Greet with alert
Combine prompt input with an alert message.
JavaScript
const name = prompt("What is your name?");
if (name !== null && name.trim() !== "") {
alert("Nice to meet you, " + name + "!");
} else {
alert("No name provided.");
}
Both block. Second dialog waits for the first to finish.
Example 4 — Validate a Number
Re-prompt until a positive number is entered, or stop on Cancel.
JavaScript
let age;
do {
age = prompt("Enter your age (positive number):");
if (age === null) break;
} while (age.trim() === "" || isNaN(Number(age)) || Number(age) <= 0);
if (age !== null) {
console.log("Valid age:", age);
} else {
console.log("Canceled");
}
Loop. Keep asking until input is valid or canceled.
Break on null. Cancel exits cleanly.
Cast + check. Use Number and reject blanks / NaN / ≤ 0.
Report. Show the accepted age or a cancel message.
Example 5 — Favorite Color
Ask with a default and write the answer into the page.
JavaScript
const color = prompt("What is your favorite color?", "Blue");
if (color === null) {
console.log("No color chosen.");
} else {
console.log("Favorite color:", color);
}