In this article, you will learn how user interaction happens in JavaScript using alert, prompt and confirm functions.

JavaScript has 3 Types of Dialog Boxes

Alert Function

It displays the message in Alert Dialog Box. Once triggered, it waits until the user presses “OK” or dismisses the dialog box.

Syntax 💻

alert();
alert(message);

Example 😍

Click/tap on 👆🏻 above buttons to understand how alert() function works. This is a live example which executes below JavaScript code.

alert(); // Button: Alert without Message - No message is passed
alert("Hello World"); // Button: Alert with Message - Displays "Hello World"

Prompt Function

In addition to displaying the message in a Dialog Box, the prompt function also accepts text from the user. Once triggered, it waits until the user presses “OK” or Cancels the dialog box.

Syntax 💻

prompt(message);
prompt(message, default);

The prompt() function returns string if user enters text and clicked “OK” otherwise null if the user clicked “Cancel”.

In case, if you want to work with numeric value then you may need to convert the accepted value into number, explicitly.

Here, “default” is an optional argument which displays the default value in the textbox of the dialog box.

Example 1 😍

Click/tap on 👆🏻 above button to understand how prompt() function works when we don’t pass default value as an argument. This is a live example which executes below JavaScript code.

let clrName = prompt('What\'s your favorite color?');
alert("Wow.. 😍 Your favorite color is " + clrName);

Example 2 😍

Click/tap on 👆🏻 above button to understand how prompt() function works when we pass the default value.

You will notice that the textbox in the dialog box already contains the default value passed as an argument.

let clrName = prompt('What\'s your favorite color?', 'Red');
alert("Wow.. 😍 Your favorite color is " + clrName);

Confirm Function

As the name states, the confirm() function is used for confirmation purpose. Once triggered, it waits until the user confirms or cancels the dialog box.

Confirm indicates boolean true while Cancel indicates boolean false.

Syntax 💻

confirm(message);

Example 😍

Click/tap on 👆🏻 above button to understand how confirm() function works. This is a live example which executes below JavaScript code.

let res = confirm('Are you sure, you want to exit?');
alert("You opted with " + res);

Summary 📖

Alert

To show a message.

Prompt

To show a message accepted from the user through textbox. It returns the text or, if Cancel button or Esc key is clicked, null.

Confirm

To show a message and wait for the user to press “OK” or “Cancel”. It returns true if OK is clicked and false if Cancel is clicked or Esc key is pressed.


This is how a user can interact in JavaScript with the help of alert, prompt and confirm functions. For more JavaScript related posts, click here.

Categorized in: