JS Popup Boxes
In this page:
window.alert("message");
const ok = window.confirm("message");
const text = window.prompt("message", "default");
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.
उदाहरण: The Three Popup Functions
// Call `document.alert("Message with OK button")`
// Call `document.alert("Message with OK button")`
window.alert("Message with OK button");
// Declare the constant `confirmed`, set to `window.confirm("Are you sure?")`
// Declare the constant `confirmed`, set to `window.confirm("Are you sure?")`
const confirmed = window.confirm("Are you sure?");
// Declare the constant `name`, set to `window.prompt("Enter your name:")`
// Declare the constant `name`, set to `window.prompt("Enter your name:")`
const name = window.prompt("Enter your name:");
// Print `confirmed, name` to the console
// Print `confirmed, name` to the console
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.
उदाहरण: 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.
उदाहरण: 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.
उदाहरण: 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.
उदाहरण: 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: