What is the difference between the alert() and confirm() methods?

These are two of the dialog windows built directly into JavaScript itself. The difference between them is in what fields they contain and also in what you should use them for. In each case the actual controls that the dialog supplies and how the dialog looks are determined by the browser and you only get to supply the text that appears in the message in the dialog.

The main use for any of the dialogs in modern JavaScript is as a simple debugging tool for when you can't be bothered to open the full debugger that modern browsers supply (it is particularly useful for those who haven't yet learnt to use the debugger). Where you actually want to display a modal dialog as a regular part of your web page modern practice is to use a lightbox script that allows you to define exactly how you want the dialog to appear using HTML. Some browsers now implement the built in dialogs as if they were predefined lightbox dialogs.

The only other use that these dialogs have is in sample scripts where the sample may use an alert as a placeholder for whatever code would go at that point in a complete script.

Alert

This is the simplest of the dialogs that browsers supply for use with JavaScript running in a browser. In its simplest form the alert dialog consists simply of the text you supply and an OK button to close the dialog.

As these dialogs are now intended primarily for debugging purposes some browsers now provide an additional option in an alert dialog either to suppress further displays of dialogs or to disable JavaScript on the web page completely. This makes the dialogs more useful for testing for the cause of why your script is getting stuck in a loop.

To use an alert for debugging purposes you can either have it display a fixed value to tell you that the script execution actually passed through that spot in the code or you can display a variable in order to see what value it contained at that time.

Confirm

This dialog differs from the alert in that it contains one extra button labelled 'Cancel'. This call also returns a value which will be false if the Cancel button was pressed and True otherwise (either the Ok button was pressed or the option to disable future dialogs was selected).

This dialog is unlikely to get used very much. About the only time I can think of where it would be useful is if you are trying to debug code that is getting stuck in a loop using a browser that still hasn't added the additional debugging options to the dialogs. In that instance you could use the following to allow the Cancel button to force the script out of the loop.

if (!confirm(x)) break;

There are other dialogs that are also built into browsers but those now serve no useful purpose and so should not be used.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate