Confirm in JavaScript Tutorial

In this section, we will learn what the confirm() method is and how to use it in JavaScript.

JavaScript Window confirm() Method

The `confirm()` function is used to display a message to users via a dialog box.

We usually use this method when we want users to confirm or verify something.

The dialog that will appear to users has 2 buttons:

  • OK
  • Cancel

If the user presses the `OK` button, the return value of this function is `true` and if she presses the `Cancel` button, the return value of the function will be `false`.

Notes:

  • The dialog that will appear to the user is synchronous. This means code execution stops when a dialog is displayed, and resumes after it has been dismissed.
  • Also, the shape of this dialog is system dependent and we can’t change it via CSS.

Window confirm() Method Syntax:

confirm(message)

Window confirm() Method Parameter

The method takes one argument and that is the message (String value) that we want to display to users.

Window confirm() Method Return Value

The return value of the confirm() method is a boolean value:

  • If the value is `true` that means users pressed the OK button of the dialog box.
  • if the value is `false` that means users pressed the Cancel button of the dialog box.

Example: confirm box in JavaScript

console.log("Start");
if (confirm("Are you sure you want to proceed?")){
  alert("Welcome :)");
}else{
  alert("Good Bye");
}
console.log("End");

The moment we run the program, a confirmation message will appear. If we hit the `OK` button, then the return value of the `confirm()` function becomes true and the body of the `if` statement will run (which is an alert message saying `Welcome`). On the other hand, if we call the `Cancel` button, the result of the `confirm()` function becomes false and the body of the `else` statement will run instead.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies