How do you open a confirm window in JavaScript?

Understanding the Javascript confirm() Function

In JavaScript, the confirm() function is a method that presents a dialog box with an optional message and two buttons: OK and Cancel. When the confirm() function is called in a JavaScript code, it opens a pop-up window or confirmation dialog box in the browser. The syntax is simple, you just need to use confirm(Your Message Here). This makes confirm() the right approach, as referred in the quiz question, to open a confirmation dialog box in JavaScript.

In a typical use case, the confirm() method returns a boolean (true or false) based on the user's choice. If the user clicks OK, the method will return true; if the user clicks Cancel or closes the dialog box, the function will return false.

Here's an example of how it can be employed:

let userChoice = confirm("Do you wish to proceed?");

if (userChoice){
    alert("You chose to proceed.");
} else {
    alert("You chose to cancel.");
}

In this example, the JavaScript confirm() method is used to give the user a choice to proceed or not. A message is shown in the confirmation dialog box, and depending on the user's response, different alerts will be shown.

It's important to remember that confirm() is a function of the window object, and hence it is global. That's why functions like location.confirm(), window.open_confirm(), or window.new_confirm() do not exist or will not yield a confirmation dialog box. Always use confirm() to generate confirmation dialogs.

The confirm(), alert() and prompt() are all part of JavaScript's "old-school" interactive functions, and while useful, they may be styled differently depending on the browser in use. Native JavaScript functions like confirm() are not customizable in style, which is why some developers may prefer to use more flexible, custom confirmation dialogs presented by various JavaScript libraries and frameworks.

Best Practices

While confirm() is handy for simple interactions, its usage in modern web development is generally discouraged for a couple of reasons:

  • For one, it's blocking, which means it stops the execution of the script and permits no other activity until the user responds.
  • Secondly, it could lead to some usability issues on mobile, as it does not always translate well to mobile devices' user interfaces.

For these reasons, developers generally prefer non-blocking, customizable and more advanced solutions provided by libraries like Bootbox.js, SweetAlert, or even leveraging the modal functionality in UI libraries/frameworks such as Bootstrap or Material-UI.

However, for simple interactions or debugging sessions, the JavaScript confirm() method remains a quick and easy to understand tool.

Do you find this helpful?