How to use window.confirm()

How to use the confirm() method offered by browsers to allow the user to confirm

· 1 min read
How to use window.confirm()

Window.confirm() shows us a dialog window with an optional message and two buttons, OK and Cancel.

This method is supported by all browsers.

It is very simple and I think it can be useful in many cases without having to resort to a custom user interface.

This is how it works: We pass a string to confirm, and this string will be displayed to the user in a message with two buttons, OK and Cancel.

confirm('Are you sure you want to delete this item?')

The browser blocks the execution of the script until the user clicks on either the OK or Cancel button. You can't get away from that without clicking a button.

The call returns a Boolean value, if the user clicks OK it returns a value true , if they click Cancel it returns a value false, so we can assign it to a variable confirm()or we can use it in a conditional.

const confirmado = confirm('Are you sure you want to delete this item?')
if (confirm('Are you sure you want to delete this item?')) {
  console.log('Confirmed')
}