How to Show Popup Messages in JavaScript

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

JavaScript provides built-in global functions that allow developers to interact with users through simple popup message boxes. These functions are commonly used for displaying messages, confirming actions, or capturing input.


1. alert() – Display an Informational Message

The alert() function is used to show a message to the user in a popup dialog box with an OK button. It is typically used for informational messages or notifications that don't require any user input.

Syntax:

  window.alert(message);

Note: The window object is optional, as these are global functions. You can simply write alert(message);.

Examples:

alert("This is an alert message.");  // Displays a simple message
    alert("The number is: " + 100);      // Concatenates and displays a message
    alert(100);                          // Displays a number
    alert(Date());                       // Displays the current date and time

2. confirm() – Ask for User Confirmation

The confirm() function is used to ask the user for confirmation before proceeding with an action, such as deleting a record or saving changes. It shows a dialog with OK and Cancel buttons.

Syntax:

var result = window.confirm(message);
  • Returns true if the user clicks OK

  • Returns false if the user clicks Cancel

Example:

 var userResponse;

    if (confirm("Do you want to save the changes?")) {
        userResponse = "Changes saved successfully!";
    } else {
        userResponse = "Save operation canceled.";
    }

3. prompt() – Get Input from the User

The prompt() function allows you to capture input from the user. It displays a dialog box with a message, a text input field, and OK and Cancel buttons.

Syntax:

var input = window.prompt(message, defaultValue);
  • message (optional): The message to display in the dialog.

  • defaultValue (optional): A default value shown in the input field.

Example:

var name = prompt("Enter your name:", "John");

    if (name === null || name.trim() === "") {
        document.getElementById("msg").innerHTML = "You didn't enter anything. Please try again.";
    } else {
        document.getElementById("msg").innerHTML = "You entered: " + name;
    }

Summary

FunctionPurposeButtons ShownReturn Value
alert()Display an informational messageOKundefined
confirm()Ask for confirmationOK, Canceltrue or false
prompt()Capture user inputOK, Cancel + inputInput string or null





These message boxes provide simple ways to interact with users and are often used in forms, validation checks, and user interaction prompts.