JavaScript Simple Actions: alert()
, prompt()
, and confirm()
JavaScript provides three built-in dialog functions for user interaction:
alert()
– Displays a simple message.prompt()
– Asks for user input.confirm()
– Requests confirmation (OK/Cancel).
š¹ 1. alert()
– Display a Message
The alert()
function shows a popup message with an "OK" button. It is commonly used to show notifications or warnings.
✔ Example:
š Output:
A pop-up box with "Welcome to JavaScript!"
and an OK button.
š¹ 2. prompt()
– Ask for User Input
The prompt()
function displays a dialog box asking the user to enter some text.
It returns:
✅ The text entered by the user.
❌ null
if the user clicks Cancel.
✔ Example:
š Output:
- A pop-up appears:
"What is your name?"
with a text box. - If the user types
"John"
and clicks OK, the next alert will show:
š"Hello, John!"
✔ Example with Default Value:
š Output:
If the user doesn't change "18"
and presses OK, it will show:
š "Your age is 18"
š¹ 3. confirm()
– Ask for Confirmation
The confirm()
function asks the user to confirm an action.
It returns:
✅ true
if the user clicks OK.
❌ false
if the user clicks Cancel.
✔ Example:
š Output:
- A dialog box appears with:
"Are you sure you want to delete?"
- If the user clicks OK, it shows
"Item deleted!"
- If the user clicks Cancel, it shows
"Action canceled."
š¹ Summary Table
Function | Purpose | Returns |
---|---|---|
alert("Message") | Displays a message | Nothing (undefined ) |
prompt("Message") | Asks for input | String (null if canceled) |
confirm("Message") | Asks for confirmation | true (OK) / false (Cancel) |
š Use Cases
- ✅
alert()
→ Show simple notifications. - ✅
prompt()
→ Get user input before proceeding. - ✅
confirm()
→ Confirm before performing critical actions.
šÆ Practice using these methods to enhance user interaction in your JavaScript projects!