JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Popup Boxes

14 April 2025 | Category:

JavaScript provides popup boxes to interact with users — great for showing messages, taking input, or getting confirmation. These popups are built into the browser and don’t require any HTML or CSS.


📦 3 Types of JavaScript Popup Boxes

TypeDescription
alert()Shows a simple message.
confirm()Asks for confirmation (OK/Cancel).
prompt()Asks for input from the user.

🔔 1. alert() – Display a Message

The alert() method is used to show a message in a popup box. The user can only click OK to close it.

✅ Syntax

alert("This is an alert!");

✅ Example

<button onclick="alert('Hello, user!')">Show Alert</button>

Use alerts for important messages — but don’t overuse them; they can be annoying.


❓ 2. confirm() – Ask for Confirmation

The confirm() method shows a message and OK/Cancel buttons. It returns:

  • true if user clicks OK
  • false if user clicks Cancel

✅ Syntax

confirm("Are you sure?");

✅ Example

let result = confirm("Do you want to delete this?");
if (result) {
  alert("Deleted!");
} else {
  alert("Cancelled.");
}

📝 3. prompt() – Get Input from User

The prompt() method shows a box where users can enter text. It returns:

  • The input (string) if OK is clicked
  • null if Cancel is clicked

✅ Syntax

prompt("What is your name?");

✅ Example

let name = prompt("Enter your name:");
if (name !== null) {
  alert("Hello, " + name + "!");
} else {
  alert("You cancelled the prompt.");
}

🔁 Example: All Three in Action

<button onclick="showPopup()">Try All Popups</button>

<script>
function showPopup() {
  alert("Welcome to the site!");

  const confirmBox = confirm("Do you want to continue?");
  if (confirmBox) {
    const name = prompt("What's your name?");
    if (name) {
      alert("Hello, " + name + "!");
    } else {
      alert("No name entered.");
    }
  } else {
    alert("You chose to cancel.");
  }
}
</script>

⚠️ Important Notes

  • Popups pause code execution until the user responds.
  • Most modern browsers block popups if triggered automatically (not by a user click).
  • Popups are synchronous, meaning the next line waits until the popup is closed.

✅ Summary

PopupPurposeReturns
alert()Show messageNothing
confirm()Ask yes/notrue / false
prompt()Get user inputInput / null