An alert in JavaScript is a method used to display a message box with a specified message and an OK button. It's commonly used to provide information to the user or to prompt them for some action.
Syntax:
alert("Your message goes here");
Basic Alert
The alert()
function is used to display a simple alert box with the message "Hello, this is an alert!". When this line of code executes, it interrupts the user's browsing experience by displaying a modal dialogue box containing the specified message. The user must click the "OK" button to dismiss the alert and continue interacting with the webpage.
Example: To demonstrate triggering an alert using JavaScript after a delay.
setTimeout(() => {
alert("Hello, this is an alert!");
}, 3000);
Output:
Alert with Dynamic Content
The alert() function can also be used to display the dynamic content, which is concatenated with the message inside the alert()
function to create a personalized alert message.
Example: To demonstrate triggering an alert with the dynamic content using JavaScript after a delay.
let userName = "John";
setTimeout(() => {
alert("Hello, " + userName + "! Welcome to our website.");
}, 3000)
Output