JavaScript Message Boxes: alert(), confirm(), and prompt()
JavaScript provides built-in global functions that allow developers to interact with users through simple popup message boxes. These functions are commonly used for displaying messages, confirming actions, or capturing input.
1. alert() – Display an Informational Message
The alert() function is used to show a message to the user in a popup dialog box with an OK button. It is typically used for informational messages or notifications that don't require any user input.
Syntax:
Note: The
windowobject is optional, as these are global functions. You can simply writealert(message);.
Examples:
2. confirm() – Ask for User Confirmation
The confirm() function is used to ask the user for confirmation before proceeding with an action, such as deleting a record or saving changes. It shows a dialog with OK and Cancel buttons.
Syntax:
Returns
trueif the user clicks OKReturns
falseif the user clicks Cancel
Example:
3. prompt() – Get Input from the User
The prompt() function allows you to capture input from the user. It displays a dialog box with a message, a text input field, and OK and Cancel buttons.
Syntax:
message(optional): The message to display in the dialog.defaultValue(optional): A default value shown in the input field.
Example:
Summary
| Function | Purpose | Buttons Shown | Return Value |
|---|---|---|---|
alert() | Display an informational message | OK | undefined |
confirm() | Ask for confirmation | OK, Cancel | true or false |
prompt() | Capture user input | OK, Cancel + input | Input string or null |
These message boxes provide simple ways to interact with users and are often used in forms, validation checks, and user interaction prompts.
