In JavaScript, PopUps are small alert or message windows that appear on the screen to display information, ask for user input, or confirm an action. They are often used to grab the userβs attention, display warnings, or take quick responses without navigating to a new page.
There are three main types of PopUps in JavaScript:
The alert() method displays a message box with an OK button. It is often used to show information or warnings.
// Example: Using alert()
alert("Welcome to JavaScript PopUps!");
// Another example
let name = "Ayush";
alert("Hello " + name + "! Have a great day π");
β Output: A message box appears with the text inside the quotes.
The confirm() method displays a dialog box with a message and two buttons β OK
and Cancel.
It returns true if the user clicks OK and false if they click Cancel.
// Example: Using confirm()
let response = confirm("Do you want to continue?");
if (response) {
alert("You clicked OK!");
} else {
alert("You clicked Cancel!");
}
β Output: A popup asks the user to confirm, and based on their choice, a message appears.
The prompt() method displays a dialog box that asks the user to input some text.
It returns the text entered by the user, or null if the user cancels.
// Example: Using prompt()
let userName = prompt("Enter your name:");
if (userName) {
alert("Hello " + userName + "! Welcome to our site!");
} else {
alert("You didn't enter your name!");
}
β Output: A popup asks for your name, and then greets you based on your response.
Suppose you have a website where you want to confirm if a user really wants to delete a file. You can use
confirm() like this:
// Real-life example
function deleteFile() {
let confirmDelete = confirm("Are you sure you want to delete this file?");
if (confirmDelete) {
alert("File deleted successfully!");
} else {
alert("File deletion canceled.");
}
}
When you call deleteFile(), the user gets a confirmation popup before any action is performed β
improving user control and safety.
| Popup Type | Method | Description | Return Value |
|---|---|---|---|
| Alert Box | alert() | Displays a message with an OK button | Undefined |
| Confirmation Box | confirm() | Asks for confirmation (OK/Cancel) | true / false |
| Prompt Box | prompt() | Asks for user input | Entered value / null |