JS Popup Boxes
In this page:
The Three Popup Functions
JavaScript provides three built-in blocking dialogs: alert() shows a message with an OK button, confirm() asks a yes/no question and returns true or false, and prompt() asks for text input and returns the entered string or null if cancelled.
Example: The Three Popup Functions
window.alert("Message with OK button");
const confirmed = window.confirm("Are you sure?");
const name = window.prompt("Enter your name:");
console.log(confirmed, name);
Blocking, Synchronous Behavior
All three popups pause script execution entirely until the user responds, which is unusual in modern JavaScript where almost everything else (fetch, timers, event handling) is asynchronous. No other code on the page runs while one of these dialogs is open.
Example: Blocking, Synchronous Behavior
console.log("before");
window.alert("Page is paused until you click OK");
console.log("after"); // doesn't log until alert is dismissed
Return Values in Practice
alert() always returns undefined since it only has an OK button, confirm() returns a real boolean you can branch on directly, and prompt() returns either the typed string or null, which must be checked before using the result to avoid treating a cancel as an empty string.
Example: Return Values in Practice
const result = window.alert("Just OK"); // always undefined
console.log(result);
const ok = window.confirm("Proceed?");
console.log(typeof ok); // "boolean"
Styling Limitations
None of the three dialogs can be styled with CSS, repositioned, or customized beyond their text content, since they're rendered by the browser chrome itself, not the page's DOM. This is a hard limitation, not a workaround-able one.
Example: Styling Limitations
window.alert("This cannot be styled with CSS or repositioned.");
Why Production UIs Avoid Them
Because they block the entire page and can't match a site's visual design, most production interfaces build custom modal components instead, reserving the native popups mostly for quick debugging or very low-stakes internal tools where blocking behavior and default styling are acceptable tradeoffs.
Example: Why Production UIs Avoid Them
window.alert("Native popups are mostly for quick debugging.");
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: