iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Popup Alert

JavaScript has three built-in dialog functions: alert, confirm, prompt. They're useful in quick demos and absolutely banned in production UI.

The three

FunctionShowsReturns
alert("msg")A message + OK buttonundefined
confirm("Sure?")Message + OK / Canceltrue / false
prompt("Name?", "default")Message + text fieldThe string, or null if cancelled

Why they're bad for real apps

  • Block the main thread — nothing else can run.
  • Can't be styled to match the rest of the app.
  • Many browsers throw them away during repeated calls (anti-spam).
  • Inaccessible — they hijack focus and don't announce well.
  • Modal-blocking dialogs feel hostile on mobile.

Modern alternatives

NeedUse
Notice the userA toast/snackbar component, or <output role="status">
Confirm a destructive actionNative <dialog> element with focus management
Collect a valueA real form inside <dialog>

The native <dialog> element

HTML + JS
<dialog id="confirm">
  <form method="dialog">
    <p>Delete this item?</p>
    <button value="cancel">Cancel</button>
    <button value="ok">Delete</button>
  </form>
</dialog>

<script>
const dlg = document.querySelector("#confirm");
dlg.showModal();                  // open
dlg.addEventListener("close", () => console.log(dlg.returnValue));
</script>
Tip: Reach for alert only in quick scripts or learning exercises. <dialog> is now widely supported and behaves correctly for keyboard, focus, and screen readers.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Popup Alert!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Ask the user a yes/no question with the native confirm dialog.

const ok = ('Delete this item?');

Test yourself

Q1. `alert(msg)` returns…
Q2. `prompt(…)` when the user cancels returns…
Q3. Production-friendly modal alternative is…

Discussion

Loading…