JavaScript Window confirm() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Dialog box

What You’ll Learn

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

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.

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.

📝 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.

⚡ Quick Reference

TopicDetail
Call formconfirm(message)
Buttons shownOK and Cancel
OK clickedReturns true
Cancel clickedReturns false
Collects text input?No — use prompt()
Blocks script?Yes, until dismissed

📋 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

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.");
}
Try It Yourself

How It Works

The dialog blocks until the user chooses. Only when userConfirmed is true should you call your real delete function or API.

📈 Practical Patterns

Branching, forms, navigation guards, and event-driven confirms.

Example 2 — Inline if Guard

Put confirm() directly inside the condition for short handlers.

JavaScript
if (confirm("Do you want to proceed?")) {
  console.log("User confirmed — running next step.");
} else {
  console.log("User canceled — nothing changed.");
}
Try It Yourself

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.");
}
Try It Yourself

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.");
}
Try It Yourself

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>
Try It Yourself

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.

🚀 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.

📝 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.

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 Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All 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.

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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about confirm()

Your foundation for yes/no decisions in browser JavaScript.

5
Core concepts
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.

Continue to focus()

Learn how to bring a window to the front with the window.focus() method.

focus() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful