What is Popup box? What are the types of Popup box available in JavaScript?
JavaScript Popup Boxes: Definition and Types
A popup box in JavaScript is a built-in, modal dialog shown by the browser to interact with the user. It temporarily pauses script execution and user interaction with the page until the user responds. These dialogs are simple, secure, and not meant to be styled with CSS.
Types of Popup Boxes in JavaScript
- alert()
- confirm()
- prompt()
1) alert()
Purpose: Display an informational message or warning with a single “OK” button.
Returns: Nothing (undefined). Execution resumes after the user clicks OK.
Syntax:
alert("Operation completed successfully!");
Example:
// Show a simple message to the user
function showAlert() {
alert("Welcome to the site!");
}
2) confirm()
Purpose: Ask the user to confirm an action with “OK” or “Cancel”.
Returns: true if OK is clicked, false if Cancel is clicked.
Syntax:
const result = confirm("Do you want to delete this item?");
Example:
// Confirm before performing a critical action
function deleteItem() {
if (confirm("Are you sure you want to delete this item?")) {
// proceed with deletion
console.log("Item deleted.");
} else {
console.log("Deletion canceled.");
}
}
3) prompt()
Purpose: Collect a single line of text input from the user.
Returns: The entered string, or null if the user clicks Cancel or closes the dialog.
Syntax:
const name = prompt("Enter your name:", "Guest");
Example:
// Ask for user input and handle Cancel safely
function askName() {
const name = prompt("What is your name?", "Student");
if (name === null) {
console.log("User canceled.");
} else if (name.trim() === "") {
console.log("No name provided.");
} else {
console.log("Hello, " + name + "!");
}
}
Key Points and Best Practices
- These dialogs are modal and block interaction with the page until closed.
- They are controlled by the browser UI and cannot be styled with CSS.
- Use them sparingly to avoid disrupting user experience; for richer UI, use custom modals built with HTML/CSS/JS.
- Always handle false (confirm) and null (prompt) to avoid errors.
Quick Comparison
- alert(): message only, OK button, pauses script.
- confirm(): OK/Cancel, returns true/false.
- prompt(): text input, returns string or null.
