Exploring alert(), confirm() and prompt() in Javascript

alerts confirm and prompt boxes in javascript

Image by Andreas from Pixabay

There are 3 ways to interact with the user in javascript : alert(), confirm() and prompt(). All these 3 functions are built-in and provided by the browser’s javascript engine.

Let’s check the example of each popup in detail:

alert()

Javascript alert() method instructs the browser to display the dialog box with a message and wait until user dismisses the dialog. When an alert dialog box is open, user can not interact with other parts of the page. This popup allows user to switch the tabs.

See the Pen Untitled by Code Topology (@codetopology) on CodePen.

message is optional, if skipped, browser will show empty alert box. It is worth to note that alert method does not return any value.

confirm()

confirm() method instruct the browser to display the message to user and wait until user clicks on OK or Cancel buttons. This function returns true if OK is pressed or false if cancel is pressed.

See the Pen Untitled by Code Topology (@codetopology) on CodePen.

prompt()

prompt() function displays the message to the user in popup and asks user to enter some text and waits until user enters the text or cancels the dialog.

There are 3 different ways in which we can write prompt() function

prompt();
prompt(message);
prompt(message,defaultValue);

As you can see, message is an optional field. We can also pass defaultValue in the text field as shown in 3rd syntax above. This function returns string entered by user or null.

See the Pen Untitled by Code Topology (@codetopology) on CodePen.

Please note you can not change default button labels “OK”, “Cancel” in these popup boxes.

Leave a Reply

Your email address will not be published. Required fields are marked *