The confirm() method asks the user to approve or cancel an action. This tutorial covers syntax, the boolean return value, five beginner-friendly examples, how it differs from alert() and prompt(), and when to prefer custom modal UI.
01
Syntax
confirm(message)
02
Buttons
OK and Cancel
03
Return
true or false
04
Blocking
Script waits for choice
05
vs alert
Choice vs info only
06
Patterns
Delete, submit, leave
Fundamentals
Introduction
When your app is about to do something irreversible—delete a record, submit a form, or navigate away from unsaved work—you should ask the user first. The window.confirm() method is the built-in browser way to show a short question with OK and Cancel buttons and get a yes-or-no answer back as a boolean.
Like alert(), confirm() is synchronous: JavaScript stops until the user picks a button. That makes the API easy for beginners, but most production sites eventually replace it with styled in-page modals for better design and accessibility.
Concept
Understanding the confirm() Method
Pass a string (or value that converts to a string) as the message. The browser shows a modal dialog. If the user clicks OK, the method returns true. If they click Cancel or dismiss the dialog, it returns false.
The usual pattern is to store the result and branch: if (confirm("Delete?")) { /* proceed */ }. Because the dialog blocks the main thread, tie confirms to explicit user actions (button clicks) rather than firing them automatically when the page loads.
💡
Beginner Tip
confirm("Save?") and window.confirm("Save?") behave the same in browsers. Always check the returned boolean before running destructive code.
Foundation
📝 Syntax
General form of Window.confirm():
JavaScript
const ok = window.confirm(message);
// shorthand (same in browsers):
const ok = confirm(message);
Parameters
message (optional) — text shown in the dialog. Non-string values are converted with ToString.
Return value
true — user clicked OK.
false — user clicked Cancel or dismissed the dialog.
Common patterns
if (confirm("Delete item?")) { deleteItem(); } — guard destructive actions.
const ok = confirm("Submit form?"); if (ok) form.submit(); — explicit variable for readability.
button.onclick = () => { if (!confirm("Leave?")) return; navigate(); } — cancel early when user says no.
Cheat Sheet
⚡ Quick Reference
Topic
Detail
Call form
confirm(message)
Buttons shown
OK and Cancel
OK clicked
Returns true
Cancel clicked
Returns false
Collects text input?
No — use prompt()
Blocks script?
Yes, until dismissed
Compare
📋 confirm() vs alert() vs prompt()
All three are legacy modal dialogs on window. Use confirm() when you need a yes/no decision before continuing.
alert()
alert("Done!")
Message only; returns undefined
confirm()
confirm("Delete?")
OK / Cancel → boolean
prompt()
prompt("Name?")
Text field → string or null
Modern UI
<dialog>
Styled, accessible modals
Hands-On
Examples Gallery
Each snippet opens a native OK/Cancel dialog. Use the Try-it links to run them behind a button. Dialog text and possible outcomes are shown below as “View Output” for reference.
📚 Getting Started
Store the boolean result and act only when the user confirms.
Example 1 — Confirm Before Deleting an Item
Ask the user before running delete logic. Cancel keeps the item safe.
JavaScript
const userConfirmed = confirm("Are you sure you want to delete this item?");
if (userConfirmed) {
console.log("Item deleted successfully.");
} else {
console.log("Deletion canceled by the user.");
}
Do you want to proceed?
If OK → User confirmed — running next step.
If Cancel → User canceled — nothing changed.
How It Works
The confirm call evaluates to a boolean that drives the if branch. This compact style is common in tutorials and small scripts.
Example 3 — Confirm Form Submission
Double-check before sending data the user cannot easily undo.
JavaScript
const submitForm = confirm("Do you want to submit the form?");
if (submitForm) {
document.getElementById("myForm").submit();
console.log("Form submitted.");
} else {
console.log("Form submission canceled by the user.");
}
Do you want to submit the form?
If OK → Form submitted.
If Cancel → Form submission canceled by the user.
How It Works
Intercept the submit action, show the confirm dialog, and call form.submit() only when the user agrees. In HTML forms you might attach this to a button’s click handler instead of the native submit event.
Example 4 — Confirm Before Leaving a Page
Warn users before navigating away when they might lose unsaved work.
JavaScript
const leavePage = confirm("You have unsaved changes. Leave this page?");
if (leavePage) {
window.location.href = "dashboard.html";
console.log("Navigating away…");
} else {
console.log("Navigation canceled by the user.");
}
You have unsaved changes. Leave this page?
If OK → Navigating away…
If Cancel → Navigation canceled by the user.
How It Works
For link clicks you control, confirm first then set location.href. For browser back/close tab warnings, modern apps often use the beforeunload event instead of confirm().
Example 5 — Confirm on Button Click
Trigger the dialog from a user action and show the result on the page.
JavaScript
<button id="logoutBtn" type="button">Log out</button>
<p id="status"></p>
<script>
document.getElementById("logoutBtn").addEventListener("click", function () {
const ok = confirm("Log out of your account?");
document.getElementById("status").textContent = ok
? "Logged out."
: "Logout canceled.";
});
</script>
Log out of your account?
If OK → Logged out.
If Cancel → Logout canceled.
How It Works
Button clicks are the right place for confirms—the user initiated the flow. Update the DOM or call your logout API only when ok is true.
Applications
🚀 Common Use Cases
Delete confirmations — prevent accidental removal of rows, files, or accounts.
Form submission — last chance before sending payment or registration data.
Navigation guards — warn before leaving a page with unsaved edits.
Logout flows — confirm the user wants to end their session.
Bulk actions — “Apply changes to 50 items?” before running batch updates.
Learning demos — teach boolean logic and branching with visible OK/Cancel results.
🧠 What Happens When You Call confirm()
1
Convert message
The argument becomes dialog body text.
ToString
2
Open modal
Browser shows OK and Cancel controls.
UI
3
Wait for choice
JavaScript pauses until the user clicks a button or dismisses the dialog.
Sync
4
✅
Return boolean
true for OK, false for Cancel—your if branch runs next.
Important
📝 Notes
confirm() is not available in Node.js without a browser—use CLI prompts or libraries on the server.
Button labels may read “OK” / “Cancel” or localized equivalents depending on the browser language.
Dismissing via Escape or the dialog close control typically returns false, same as Cancel.
Do not nest multiple confirms in a row—it frustrates users and feels like spam.
For accessibility, native dialogs are announced, but custom modals with ARIA give you finer control.
Mobile browsers show the same API but with platform-native styling you cannot customize.
Compatibility
Browser Support
Window.confirm() has been supported in every major browser since the earliest days of JavaScript. It is part of the HTML Standard and behaves consistently across platforms.
✓ Universal · Legacy API
Window.confirm()
Supported in Chrome, Firefox, Safari, Edge, Opera, and all mobile browsers. Also available in WebViews and embedded browser controls.
100%Universal support
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
confirm()Universal
Bottom line: Safe to use anywhere a browser JavaScript environment exists. The limitation is UX and styling—not compatibility.
Wrap Up
Conclusion
The confirm() method is the built-in way to ask yes-or-no questions in browser JavaScript. It returns a boolean you can use to guard destructive or irreversible actions.
Practice with the examples above, write clear messages, and always branch on the result. When your app needs polished design, reach for custom modals—but confirm() remains a solid teaching tool and quick prototype helper.
Write clear, specific messages (“Delete 3 photos?” not “Are you sure?”)
Store the boolean and branch with if/else
Trigger confirms from user clicks, not on page load
Use confirm() for destructive actions; use alert() for info only
Plan to replace native dialogs with accessible custom UI in production
❌ Don’t
Ignore the return value and run dangerous code anyway
Chain many confirms back-to-back
Expect to style the native dialog with CSS
Use confirm() when you need text input—use prompt()
Rely on confirms alone for critical accessibility requirements
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about confirm()
Your foundation for yes/no decisions in browser JavaScript.
5
Core concepts
📝01
Syntax
confirm(message)
API
✅02
OK
Returns true.
Boolean
❌03
Cancel
Returns false.
Boolean
🚫04
Blocking
Pauses script.
Sync
🔄05
vs alert
Choice vs info.
Compare
❓ Frequently Asked Questions
It opens a modal dialog with your message and two buttons—OK and Cancel. The method returns true if the user clicks OK and false if they click Cancel or dismiss the dialog.
A boolean: true for OK, false for Cancel. Store the result in a variable and use if/else to run different code paths.
Yes. JavaScript pauses until the user chooses OK or Cancel. Avoid calling confirm() inside tight loops or on every page load.
No. Native confirm boxes use the browser's built-in UI. For custom styling, build a modal with HTML, CSS, and JavaScript—or use the HTML dialog element.
Use alert() to display information only. Use confirm() when you need the user to approve or reject an action—such as deleting a row or leaving a form with unsaved changes.
Both work in browsers because confirm is a method on the global window object. window.confirm(message) is explicit; confirm(message) is the common shorthand.
Did you know?
The trio alert(), confirm(), and prompt() were among the first ways web pages could talk back to users—years before single-page apps and component libraries made custom modals the default choice.