6. prompt and alert in JavaScript
prompt
Function:
The prompt
function is used to display a dialog box that prompts the user for input. It takes two optional parameters:
Message (prompt text): A string that will be displayed as a message in the prompt dialog.
Default (default value): A string that will be displayed in the input field as the default value.
The prompt
function returns the text entered by the user as a string. Here's an example:
let userName = prompt("Please enter your name:", "John Doe");
if (userName !== null) {
console.log("Hello, " + userName + "!");
} else {
console.log("User cancelled the prompt.");
}
In this example, the prompt
function displays a dialog asking the user to enter their name. The default value is set to "John Doe." If the user clicks "OK" after entering their name, the entered text is stored in the variable userName
. If the user clicks "Cancel" or closes the prompt, userName
will be null
.
alert
Function:
The alert
function is used to display a simple dialog box that contains a message. It takes one parameter:
- Message (alert text): A string that will be displayed as a message in the alert dialog.
Here's an example:
let message = "Welcome to our website!";
alert(message);
In this example, the alert
function displays a dialog with the message "Welcome to our website!".
Note:
Both
prompt
andalert
are blocking functions, meaning that they halt the execution of the script until the user interacts with the dialog.The user can click "OK" or "Cancel" on the prompt dialog. If "OK" is clicked, the entered value is returned; if "Cancel" is clicked,
null
is returned.The
alert
function only has an "OK" button, and it does not return any value.
It's important to use these functions judiciously, as excessive use of blocking dialogs can disrupt the user experience. Modern web development often prefers asynchronous approaches using events and callbacks for a smoother interaction flow.
Subscribe to my newsletter
Read articles from Shofique Rian directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by