Alert, Confirm, and Prompt
You'll learn how to use browser dialog boxes for simple user interaction and understand their blocking behavior.
What Are Browser Dialogs?
The window object provides three methods for quick, simple interactions with users: alert(), confirm(), and prompt(). These pop up modal dialog boxes that temporarily halt JavaScript execution until the user responds.
Alert: One-Way Communication
alert() displays a message to the user with an "OK" button:
alert("Your changes have been saved!");
// Code here won't run until user clicks OK
Think of it as a loudspeaker announcement—information goes one way, and everything stops until acknowledged.
Confirm: Yes/No Questions
confirm() asks a question and returns true if the user clicks "OK" or false if they click "Cancel":
const shouldDelete = confirm("Are you sure you want to delete this?");
if (shouldDelete) {
// User clicked OK
console.log("Deleting...");
} else {
// User clicked Cancel
console.log("Cancelled");
}
Prompt: Collecting Input
prompt() asks for text input and returns the entered string, or null if cancelled:
const userName = prompt("What is your name?", "Guest");
// Second parameter is the default value
if (userName !== null) {
alert("Hello, " + userName + "!");
}
The Blocking Problem
These methods block execution—all JavaScript stops running until the dialog is dismissed. The page becomes unresponsive, timers pause, and animations freeze. This makes them unsuitable for modern applications but handy for quick debugging or simple scripts.
Key Takeaway: Browser dialogs (alert, confirm, prompt) provide simple user interaction but block all JavaScript execution until dismissed, making them appropriate only for basic scenarios or debugging.