The Alert Box vs The Prompt Box vs The Confirm Box in JavaScript

There are three types of pop-up boxes in JavaScript: Alert, Prompt, and Confirm boxes.

Usage:

  • Alert Box: An alert box is used when you want to ensure that information gets through to the user.
  • Prompt Box: A prompt box is used to have the user input a value before entering a page.
  • Confirm Box: A confirm box is used to have the user verify or accept something.

  • Alert Box: When an alert box pops up, the user must click OK to proceed.
  • Prompt Box: When a prompt box pops up, the user will have to click either OK or Cancel to proceed after entering the input value. If the user clicks OK, the box returns the input value. If the user clicks Cancel, the box returns null.
  • Confirm Box: When a confirm box pops up, the user must click either OK or Cancel to proceed. If the user clicks OK, the box returns true. If the user clicks Cancel, the box returns false.

Parameters:

  • Alert Box: The alert function takes a single parameter, which is the text displayed in the pop-up box.
  • Prompt Box: The prompt() method takes two parameters: the first is the label, which you want to display in the text box, and the second is a default string to display in the text box (optional).
  • Confirm Box: The confirm() function takes it a single argument which is the text.

Example:

//This is an alert box
alert("This is an alert!");

//This is an prompt box
var user = prompt("Please enter your name");
alert("Nice to meet you " + user);

//This is an confirm box
var result = confirm("Do you really want to leave this page?");
if (result == true) {
alert("Thanks for visiting");
}
else {
alert("Thanks for staying with us");
}

Leave a Reply