Home JavaScript Tutorial Alert, Prompt And Confirm In JavaScript

Alert, Prompt And Confirm In JavaScript

by Ankit Chauhan
2 minutes read

In this tutorial, you’ll learn about Alert, Prompt And Confirm In JavaScript with examples.

JavaScript Alert

JavaScript Alert is a method used to display a message to the user through a pop-up box. The alert box is used to inform the user of some information or to give the user some instructions.

The syntax of the alert method is:

alert("Message to be displayed");

Here’s an example of using the alert method:

alert("Hello, World!");

When this code is executed, a pop-up box with the message “Hello, World!” will appear on the screen.

JavaScript Prompt

JavaScript Prompt is a method used to get input from the user through a pop-up box. The prompt box is used to ask the user for input on a particular topic.

The syntax of the prompt method is:

prompt("Message to be displayed", "Default text");

The first parameter is the message to be displayed, while the second parameter is the default text that will appear in the input field.

Here’s an example of using the prompt method:

let name = prompt("What is your name?", "John Doe");
alert("Hello, " + name + "!");

When this code is executed, a pop-up box will appear with the message “What is your name?” and an input field. If the user enters their name in the input field, the variable name will be assigned the value of the input. If the user clicks the “Cancel” button, the variable name will be assigned null. The next line of code will then display an alert with the message “Hello, ” followed by the value of the name variable.

JavaScript Confirm

JavaScript Confirm is a method used to get a yes or no answer from the user through a pop-up box. The confirm box is used to ask the user to confirm an action before it is taken.

The syntax of the confirm method is:

confirm("Message to be displayed");

Here’s an example of using the confirm method:

let result = confirm("Are you sure you want to delete this item?");
if (result) {
  // Code to delete the item
} else {
  // Code to cancel the deletion
}

When this code is executed, a pop-up box will appear with the message “Are you sure you want to delete this item?” and two buttons: “OK” and “Cancel”. If the user clicks the “OK” button, the result variable will be assigned the value true. If the user clicks the “Cancel” button, the result variable will be assigned the value false. The next lines of code will then either delete the item or cancel the deletion, depending on the value of the result variable.

That’s it! With these three methods, you can easily interact with the user through pop-up boxes in JavaScript.

related posts

Leave a Comment

Enable Notifications OK No thanks