The prompt() method shows a dialog with a text field so users can type a short answer. This tutorial covers syntax, return values (string or null), default text, cancel handling, validation loops, and how it fits with alert() and confirm().
01
Syntax
prompt(msg, default)
02
OK
Returns string
03
Cancel
Returns null
04
Default
Pre-filled text
05
Blocking
Script waits for input
06
Validate
Re-prompt in a loop
Fundamentals
Introduction
Sometimes you need a quick piece of text from the user—a name, a nickname, or a search term. The window.prompt() method opens a small dialog with your question, an input box, and OK / Cancel buttons.
Like alert() and confirm(), prompt() is synchronous: JavaScript pauses until the user responds. That makes it easy to learn, but most modern websites use regular HTML form fields or custom modals instead. Still, understanding prompt() helps you read older scripts and grasp how browser dialogs work.
Concept
Understanding the prompt() Method
Call prompt(message, defaultValue). The first argument is the question shown above the input. The second argument is optional—when provided, it appears pre-filled in the text field.
When the user clicks OK, the method returns whatever they typed (including an empty string if they cleared the field). When they click Cancel or dismiss the dialog, it returns null. Always check for null before using the result in your app logic.
💡
Beginner Tip
if (value === null) detects cancel. if (!value) also treats empty string as falsy—use explicit null checks when an empty answer is valid.
message (optional) — text displayed in the dialog. Non-strings are converted with ToString.
defaultValue (optional) — initial value in the input field. Omit it for a blank field.
Return value
string — user clicked OK (may be "" if the field is empty).
null — user clicked Cancel or dismissed the dialog.
Common patterns
const name = prompt("Your name?"); if (name !== null) greet(name); — skip work on cancel.
prompt("City?", "London") — suggest a default the user can edit.
do { input = prompt("Age?"); } while (input !== null && !isValid(input)); — re-ask until valid or canceled.
Cheat Sheet
⚡ Quick Reference
Topic
Detail
Call form
prompt(message, defaultValue)
User clicks OK
Returns entered string
User clicks Cancel
Returns null
Empty OK click
Returns "" (not null)
Pre-fill input
Second argument
Blocks script?
Yes, until dismissed
Compare
📋 prompt() vs alert() vs confirm()
All three are legacy modal dialogs on window. Use prompt() when you need the user to type text.
alert()
alert("Done!")
Message only; returns undefined
confirm()
confirm("Delete?")
OK / Cancel → boolean
prompt()
prompt("Name?")
Text field → string or null
HTML input
<input>
Modern, styled, accessible
Hands-On
Examples Gallery
Each snippet opens a native input dialog. Use the Try-it links to run them behind a button. Dialog text and possible outcomes are shown below as “View Output” for reference.
📚 Getting Started
Store the returned string and use a default value to guide the user.
Example 1 — Ask for a Name with Default Text
Pre-fill the input so users can accept or edit the suggestion.
JavaScript
const userName = prompt("Please enter your name:", "Guest");
if (userName !== null) {
console.log(`Hello, ${userName}!`);
} else {
console.log("User canceled the prompt.");
}
Please enter your name: [Guest]
If OK → Hello, Guest! (or whatever they typed)
If Cancel → User canceled the prompt.
How It Works
The second argument appears in the input box. The user can keep Guest, change it, or clear it before clicking OK.
📈 Practical Patterns
Cancel checks, greetings, validation, and event-driven prompts.
Example 2 — Handle User Cancellation
Compare against null so cancel does not run your main logic.
JavaScript
const userInput = prompt("Enter something:");
if (userInput === null) {
console.log("User canceled the prompt.");
} else if (userInput === "") {
console.log("User clicked OK but left the field empty.");
} else {
console.log(`User entered: ${userInput}`);
}
Cancel → User canceled the prompt.
OK + empty → User clicked OK but left the field empty.
OK + text → User entered: (their text)
How It Works
Three outcomes are distinct: cancel (null), empty OK (""), and non-empty text. Handle each case your app needs.
Example 3 — Greet the User with alert()
Chain prompt() and alert() for a simple interactive flow.
JavaScript
const name = prompt("What is your name?");
if (name !== null && name.trim() !== "") {
alert(`Nice to meet you, ${name}!`);
} else {
alert("No name provided.");
}
1. prompt: What is your name?
2. If name given → alert: Nice to meet you, Alex!
If cancel/blank → alert: No name provided.
How It Works
trim() removes accidental spaces. This pattern is common in beginner exercises before moving to DOM input fields.
Example 4 — Validate Numeric Input in a Loop
Re-prompt until the user enters a positive number or clicks Cancel.
JavaScript
let age;
do {
age = prompt("Please 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 entered: ${age}`);
} else {
console.log("Prompt canceled.");
}
Invalid input → prompt appears again.
Valid positive number → Valid age entered: 25
Cancel → Prompt canceled.
How It Works
The do...while loop keeps asking until input passes your rules or the user cancels. Convert strings with Number() before checking with isNaN.
Example 5 — Prompt on Button Click
Trigger the dialog from a user action and show the result on the page.
JavaScript
<button id="colorBtn" type="button">Pick a color</button>
<p id="result"></p>
<script>
document.getElementById("colorBtn").addEventListener("click", function () {
const color = prompt("What is your favorite color?", "Blue");
const el = document.getElementById("result");
if (color === null) {
el.textContent = "No color chosen.";
} else {
el.textContent = "Your favorite color is: " + color;
}
});
</script>
What is your favorite color? [Blue]
If OK → Your favorite color is: Blue
If Cancel → No color chosen.
How It Works
Button clicks are the right trigger—never call prompt() on page load. Update the DOM with the returned string only when it is not null.
Applications
🚀 Common Use Cases
Learning exercises — quick scripts that ask for a name or number.
Simple demos — prototypes before building real form UI.
Admin tools — internal pages where a plain dialog is acceptable.
Rename actions — ask for a new file or layer name in a canvas app.
Search shortcuts — prompt for a query then navigate with the value.
Debugging helpers — temporary input during development (remove before shipping).
🧠 What Happens When You Call prompt()
1
User or script
Button click calls prompt(message, default).
Trigger
2
Dialog opens
Browser shows message, text field (with optional default), OK and Cancel.
UI
3
Script pauses
JavaScript waits until the user picks OK or Cancel.
Blocking
4
✎
Return value
OK → string. Cancel → null. Your code continues.
Important
📝 Notes
prompt() always returns a string or null—never a number. Convert with Number() when needed.
Some browsers may ignore or restrict dialogs in cross-origin iframes or without user gestures.
Long or multi-line input is awkward in a prompt; use <textarea> in the page instead.
Passwords should never be collected with prompt()—use a proper password field.
The dialog cannot be styled; branding and accessibility are limited compared to HTML modals.
For production UX, prefer visible form fields users can edit before submitting.
Compatibility
Browser Support
Window.prompt() is supported in every major browser. Dialog appearance follows the operating system theme.
✓ Universal · Standard API
Window.prompt()
Supported in Chrome, Firefox, Safari, Edge, Opera, and mobile browsers. Behavior matches alert() and confirm() for blocking and user-gesture expectations.
100%Universal support
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
prompt()Universal
Bottom line: Safe for tutorials and internal tools. Prefer HTML inputs for polished public-facing apps.
Wrap Up
Conclusion
window.prompt() is the browser’s built-in way to collect short text: show a question, read a string back, or detect cancel with null. Pair it with validation and clear cancel handling.
For real applications, graduate to HTML form controls and accessible modals—but mastering prompt() completes the classic trio alongside alert() and confirm().
Assume the return value is always a non-empty string
Collect passwords or sensitive data in a prompt
Rely on prompts for complex multi-field forms
Forget that empty OK returns "", not null
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about prompt()
Your foundation for collecting text with browser dialogs.
5
Core concepts
📝01
Syntax
prompt(msg, default)
API
✅02
OK
Returns string.
Value
❌03
Cancel
Returns null.
Cancel
🔄04
Default
Second argument.
Hint
🚫05
Blocking
Pauses script.
Sync
❓ Frequently Asked Questions
It opens a modal dialog with a message, a text input field, and OK/Cancel buttons. Use it to collect a short string from the user.
If the user clicks OK, it returns the text they entered (which may be an empty string). If they click Cancel or dismiss the dialog, it returns null.
null means the user canceled. An empty string "" means they clicked OK but left the field blank. Always check for null before using the value.
Yes. Pass a second argument as the default value: prompt("Your name?", "Guest"). The user can edit or clear it before clicking OK.
No. Native prompt boxes use the browser's built-in UI. For custom styling, use an HTML input, textarea, or the dialog element inside your page.
Rarely. It blocks JavaScript and looks dated. It is excellent for learning and quick prototypes; real apps usually use form fields or accessible in-page modals.
Did you know?
Together, alert(), confirm(), and prompt() complete the classic browser dialog trio—message only, yes/no, and typed text—all introduced early in the web platform for simple user interaction.