JavaScript offers a simple built-in method to ask users to confirm an action using the window.confirm()
function. This method displays a dialog box with a message, an OK button, and a Cancel button — allowing you to capture user consent before proceeding.
In this article, we’ll cover how the confirm()
method works, when to use it, and how to handle its response effectively.
What is window.confirm()
?
The window.confirm()
method is used to show a modal dialog that asks the user to make a binary decision — usually between OK (true) and Cancel (false).
Syntax:
-
If the user clicks OK, the method returns
true
. -
If the user clicks Cancel, it returns
false
.
Just like with alert()
, the window.
prefix is optional.
Why Use confirm()
?
The confirm()
dialog is used when:
-
A user needs to confirm a potentially destructive action (like delete or logout)
-
You want to pause execution until a decision is made
-
You want quick feedback without custom HTML or extra libraries
Example: Basic Confirmation Dialog
What happens:
When the button is clicked, a confirmation popup appears. The user must choose either OK or Cancel, and a corresponding message is shown afterward.
Considerations When Using confirm()
-
Blocking behavior: Just like
alert()
, it pauses script execution until a response is given. -
Not customizable: You can't change the appearance, button text, or styling.
-
Not mobile-friendly: May look inconsistent across browsers and devices.