How to use alert(), prompt(), and confirm() in JavaScript
In this shot, we will learn about the browser functions alert, prompt, and confirm.
Alert 🚨
alert → It displays a message in an alert box with an OK button. While displaying the alert box, the script execution is paused until the user presses the OK or ESC keys.
Syntax
alert(message)
Example
alert("This is an alert 🚨");
You can also pass in any JavaScript statement:
alert(2+4); //6
Or you can call a function:
function getMessage() {
return "Hi 👋 from Javascript Jeep ";
}
alert(getMessage())
To display a line break, you can use /n:
alert("Hello from /n JavaScript Jeep");
prompt
The prompt method asks the user to input a value by displaying a dialog with the OK and Cancel buttons. Script execution is paused until the user presses OK or Cancel.
Syntax
let returnValue = prompt(message, [default_value]);
message → The title to display in the dialog box.
default_value → The
The call to prompt returns either the text from the input field or
const YOB = prompt("What is your Year of Birth?", '');
If the user enters a value and presses OK, then the value stored in the age variable is user input. If the user clicks the Cancel button or Esc key, then the value of age is null.
let YOB = prompt('What is your Year of Birth?', 1900);
const currentYear = new Date().getFullYear();
if(YOB === null) {
YOB = 1900
}
alert(`You are ${currentYear - YOB} years old!`); // You are 100 years old!
Confirm
The confirm method will display a confirm box that
Syntax
let isConfirmed = confirm(question);
The confirm method returns true if OK is pressed; otherwise, it returns false.
Example
let canDelete = confirm("Do you want to delete the file?");
Conclusion
All of these methods pause the script execution and don’t allow the user to interact with the rest of the page until the window is closed.
Free Resources
- undefined by undefined