JavaScript Reference ยท Browser and Web APIs
alert(), confirm() and prompt()
Reference for the built-in dialog boxes alert(), confirm() and prompt(): syntax, return values, blocking behavior, limits and non-blocking alternatives.
alert(), confirm() and prompt() are the oldest user-interface functions in the browser. Each shows a small modal dialog drawn by the browser, stops your script until the user answers, and then returns. alert() shows a message, confirm() asks an OK or Cancel question, and prompt() asks for a line of text.
They are handy for quick experiments and debugging, but they have real drawbacks: you cannot style them, they freeze the page, browsers may suppress them (for example in background tabs or after repeated use), and embedded or sandboxed frames often block them. For production interfaces, a <dialog> element is usually the better choice.
alert("Saved!"); const ok = confirm("Delete this file?"); const name = prompt("Your name?", "Ada");
Try it
The preview sandbox blocks modal dialogs, so the calls return immediately with their "dismissed" results: undefined, false and null. On an ordinary page you would see real dialogs.
This helper returns a promise, so the page stays responsive and you can style the dialog freely. The helper clears returnValue before each use, because pressing Escape closes a dialog without changing it; an empty value then counts as a cancel.
Syntax
alert(message) confirm(message) prompt(message) prompt(message, defaultValue)
| Name | Description |
|---|---|
message |
Text to display. Non-strings are converted to strings. Line breaks (\n) are honored; HTML is not. |
defaultValue |
Optional. For prompt(), the text pre-filled in the input box. |
Return value:
alert()returnsundefined.confirm()returnstruefor OK andfalsefor Cancel.prompt()returns the entered string (possibly empty), ornullif the user cancels.
Usage notes
- Blocking. The page cannot repaint or run other JavaScript while a dialog is open. Timers wait, and network callbacks queue up.
- Always handle
nullfromprompt(). An empty string andnullmean different things: the user pressed OK without typing, or cancelled. prompt()always returns text. Convert numbers yourself withNumber()and check forNaN.- Browsers can suppress dialogs. Chrome, Firefox and Safari may ignore them in hidden tabs, cross-origin iframes or after repeated use, and sandboxed frames without the modal permission block them. Code that depends on
confirm()for safety checks therefore needs a fallback. - Not for accessibility-rich UI. You cannot add labels, validation, buttons or focus management. Use
<dialog>for that. - Debugging.
console.log()does not interrupt the program, which makes it better for tracing. - Same family.
window.print()also blocks the page while its dialog is open.
Browser support
Available in every browser, but dialogs are restricted or ignored in many embedded and sandboxed contexts.