JavaScript Message Boxes: alert(), confirm(), prompt()

JavaScript provides built-in global functions to display messages to users for different purposes, e.g., displaying a simple message or displaying a message and take the user's confirmation or displaying a popup to take the user's input value.

Alert Box

Use the alert() function to display a message to the user that requires their attention. This alert box will have the OK button to close the alert box.

Example: JavaScript Alert Message
alert("This is an alert message box.");  // display string message

alert('This is a numer: ' + 100); // display result of a concatenation

alert(100); // display number

alert(Date()); // display current date

The alert() function takes a paramter of any type e.g., string, number, boolean etc. So, no need to convert a non-string type to a string type.

Confirm Box

Sometimes you need to take the user's confirmation to proceed. For example, you want to take the user's confirmation before saving updated data or deleting existing data. In this scenario, use the built-in function confirm().

The confirm() function displays a popup message to the user with two buttons, OK and Cancel. The confirm() function returns true if a user has clicked on the OK button or returns false if clicked on the Cancel button. You can use the return value to process further.

The following example demonstrates how to display a confirm box and then checks which button the user has clicked.

Example: Confirm Box
var userPreference;

if (confirm("Do you want to save changes?") == true) {
    userPreference = "Data saved successfully!";
} else {
    userPreference = "Save Cancelled!";
}

Prompt Box

Sometimes you may need to take the user's input to do further actions. For example, you want to calculate EMI based on the user's preferred tenure of the loan. For this kind of scenario, use the built-in function prompt().

Syntax:
prompt([string message], [string defaultValue]);

The prompt() function takes two string parameters. The first parameter is the message to be displayed, and the second parameter is the default value which will be in input text when the message is displayed.

Example: Take User's Input using prompt()
var tenure = prompt("Please enter preferred tenure in years", "15");
    
if (tenure != null) {
    alert("You have entered " + tenure + " years" );
}

In the above example, the first parameter is a message, and the second parameter is "15" which will be shown to users by default. The prompt() function returns a user entered value. If a user has not entered anything, then it returns null. So it is recommended to check null before proceeding.

Note:
The alert(), confirm(), and prompt() functions are global functions. So, they can be called using the window object e.g. window.alert(), window.confirm(), and window.prompt().
Want to check how much you know JavaScript?