How to Use Confirm in JavaScript: Simple Guide
Use the
confirm() function in JavaScript to show a dialog box with OK and Cancel buttons. It returns true if the user clicks OK, and false if Cancel is clicked.Syntax
The confirm() function takes one argument: a message string to display in the dialog box. It returns a boolean value based on the user's choice.
- Message: Text shown to the user.
- Return value:
trueif OK clicked,falseif Cancel clicked.
javascript
confirm(message);
Example
This example shows a confirmation dialog asking if the user wants to proceed. It then logs the user's choice.
javascript
const userConfirmed = confirm('Do you want to continue?'); if (userConfirmed) { console.log('User clicked OK'); } else { console.log('User clicked Cancel'); }
Output
User clicked OK (if OK pressed) or User clicked Cancel (if Cancel pressed)
Common Pitfalls
Some common mistakes when using confirm() include:
- Not handling the return value, so the program ignores the user's choice.
- Using
confirm()in environments where dialogs are blocked or unsupported (like some browsers or automated tests). - Expecting
confirm()to be asynchronous; it actually pauses code execution until the user responds.
javascript
/* Wrong: ignoring return value */ confirm('Are you sure?'); console.log('This runs regardless of user choice'); /* Right: using return value */ if (confirm('Are you sure?')) { console.log('User agreed'); } else { console.log('User canceled'); }
Output
User agreed (if OK pressed) or User canceled (if Cancel pressed)
Quick Reference
| Feature | Description |
|---|---|
| Function | confirm(message) |
| Parameter | message (string) to show in dialog |
| Return Value | true if OK clicked, false if Cancel clicked |
| Behavior | Pauses code execution until user responds |
| Use Case | Ask user to confirm an action |
Key Takeaways
Use confirm() to show a simple OK/Cancel dialog to the user.
Always check the boolean return value to know the user's choice.
confirm() pauses code execution until the user responds.
Avoid ignoring the return value to handle user decisions properly.
confirm() may not work in all environments or browsers.