Complete JavaScript Course Module 10: Intermediate: The Browser Object Model (BOM)

JavaScript Popup Boxes: alert, confirm and prompt in Depth

  • Beginner
  • Lesson 10.5
  • 6 min read
  • 45 of 76 in the course

In short

JavaScript popup boxes are alert, confirm and prompt: small built-in dialogs that show a message, ask yes or no, or ask for text. Learn their return values, why they block the page, and when to use the dialog element instead. What are the three JavaScript popup boxes?

JavaScript popup boxes are alert, confirm and prompt: small built-in dialogs that show a message, ask yes or no, or ask for text. Learn their return values, why they block the page, and when to use the dialog element instead.

What are the three JavaScript popup boxes?

You met these boxes briefly in the first lessons of this course. They are all methods of the window object, so alert() and window.alert() are the same thing. Here they are side by side:

BoxButtonsReturnsUse it to
alert(message)OKundefinedShow a message
confirm(message)OK, Canceltrue or falseAsk a yes/no question
prompt(message, default)OK, Cancel, text boxA string, or nullAsk for a short text answer

The browser draws these boxes itself, so you cannot change their colours, fonts or button labels. They also look different in Chrome, Firefox and Safari.

How to use alert() to show a message

alert() shows a message with an OK button. It always returns undefined, so there is nothing to store.

alert("Your profile has been saved.");

// Line breaks with \n
alert("Order summary:\n- 2 x Coffee\n- 1 x Croissant\n\nTotal: €7.40");

// Non-string values are converted to text
alert(42);                    // shows: 42
alert({ name: "Maya" });      // shows: [object Object]
alert(JSON.stringify({ name: "Maya" })); // shows: {"name":"Maya"}

\n is a new line character, so the order summary appears on several lines. Notice that alerting an object shows the unhelpful [object Object]; use JSON.stringify or, much better, console.log while debugging.

Tip: Do not use alert() for debugging. console.log() is faster, shows objects properly and does not stop your page. Use alert only for quick experiments.

How to use confirm() for yes/no questions

confirm() returns true if the user clicks OK and false if they click Cancel or press Escape. That makes it perfect for an if statement:

<!DOCTYPE html>
<html lang="en">
<body>
  <ul id="contacts">
    <li>Anna <button class="delete">Delete</button></li>
    <li>Ben <button class="delete">Delete</button></li>
  </ul>

  <script>
    document.querySelector("#contacts").addEventListener("click", (event) => {
      if (!event.target.matches(".delete")) return;

      const item = event.target.closest("li");
      const name = item.firstChild.textContent.trim();

      const sure = confirm(`Delete ${name} from your contacts?\nThis cannot be undone.`);
      if (sure) {
        item.remove();
        console.log(`${name} deleted`);
      } else {
        console.log("Nothing deleted");
      }
    });
  </script>
</body>
</html>

Click "Delete" next to Anna: a box asks "Delete Anna from your contacts?". Click OK and the line disappears; the console shows "Anna deleted". Click Cancel and nothing changes. This uses event delegation, which you learned in the Event Object lesson.

How to use prompt() and check what the user typed

prompt() shows a text box. The second argument is an optional default value. It returns:

  • the typed text as a string (even if the user types numbers),
  • an empty string "" if they click OK without typing,
  • null if they click Cancel or press Escape.

You must handle all three cases:

const answer = prompt("How many tickets would you like? (1-10)", "1");

if (answer === null) {
  console.log("The user cancelled.");
} else if (answer.trim() === "") {
  console.log("The user did not type anything.");
} else {
  const tickets = Number(answer);
  if (Number.isInteger(tickets) && tickets >= 1 && tickets <= 10) {
    console.log(`Booking ${tickets} ticket(s). Total: €${tickets * 12}`);
  } else {
    console.log("Please enter a whole number from 1 to 10.");
  }
}
// Output (if the user types 3): Booking 3 ticket(s). Total: €36

We check null first, because calling .trim() on null would crash. Then we convert the string with Number() and validate it. Run it a few times in the console with different answers to see each branch.

Common mistake: Writing if (answer) and assuming that means "the user typed a number". The string "0" is truthy, "" is falsy, and "abc" is truthy but not a number. Check null, empty text and the number separately.

Why popup boxes block the page and when they are acceptable

These boxes are modal and blocking. Modal means the user cannot click anything else on the page until they answer. Blocking means your JavaScript stops at that line and waits:

console.log("Before");
alert("The script is paused until you click OK");
console.log("After");
// Output: Before
// (the box waits...)
// Output: After

While the box is open, timers, animations and other code on the page are frozen too. This, and the fact that you cannot style them, is why real websites rarely use them. Some browsers also let users tick "Prevent this page from creating additional dialogs", and browsers ignore these boxes in some situations, such as inside cross-origin iframes or when the tab is in the background.

They are still acceptable for:

  • Learning and quick experiments, like in this course.
  • Simple internal tools where looks do not matter.
  • A last-chance confirm() before a destructive action in a small project.

The modern replacement: the HTML dialog element

The <dialog> element gives you a real popup that you can style, fill with any HTML, and use without blocking your script. showModal() opens it as a modal with a dark backdrop, Escape closes it, and a form with method="dialog" closes it and remembers which button was clicked.

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    dialog { border: none; border-radius: 12px; padding: 24px; max-width: 320px; }
    dialog::backdrop { background: rgb(0 0 0 / 0.5); }
    .danger { background: crimson; color: white; }
  </style>
</head>
<body>
  <button id="deleteAccount">Delete my account</button>
  <p id="result"></p>

  <dialog id="confirmBox">
    <form method="dialog">
      <h2>Delete account?</h2>
      <p>All your photos and messages will be removed.</p>
      <button value="cancel">Cancel</button>
      <button value="delete" class="danger">Yes, delete</button>
    </form>
  </dialog>

  <script>
    const dialog = document.querySelector("#confirmBox");
    const result = document.querySelector("#result");

    document.querySelector("#deleteAccount").addEventListener("click", () => {
      dialog.showModal();          // open it; the script does NOT pause here
    });

    dialog.addEventListener("close", () => {
      // returnValue is the value of the button that closed it ("" if Escape)
      result.textContent = dialog.returnValue === "delete"
        ? "Account deleted."
        : "Phew, nothing was deleted.";
    });
  </script>
</body>
</html>

Click the button and a styled box appears over a dimmed page. Click "Yes, delete" and the page says "Account deleted."; click Cancel or press Escape and it says "Phew, nothing was deleted." Because showModal() does not block, we react to the answer in the close event instead of on the next line. The <dialog> element works in all modern browsers and handles keyboard focus for you, which makes it accessible.

Practice exercise

Write a tiny "rename file" feature. A button calls prompt("New file name:", "notes.txt"). If the user cancels, do nothing. If the name is empty, show an alert saying the name cannot be empty. Otherwise, ask confirm("Rename to " + name + "?") and, if true, show the new name on the page. Then rebuild the same feature with a <dialog> that contains an <input> and two buttons.

Hint: in the dialog version, read the input's value inside the close event when dialog.returnValue is your "save" button's value.

Key takeaways

  • alert returns undefined, confirm returns true or false, and prompt returns a string or null.
  • Use \n for line breaks; you cannot style the boxes or change their buttons.
  • Always check prompt for null, empty text and invalid numbers.
  • The boxes block the page and pause your script, so use them only for learning, quick tools or simple confirmations.
  • The <dialog> element with showModal() is the modern, stylable, non-blocking replacement.