How to Create an Alert in JavaScript ?

The alert() method in JavaScript displays an alert box with a message and an OK button. It’s used when you want information to come through to the user, providing immediate notifications or prompts for user interaction during program execution.

Note: Alert boxes interrupt user interaction, shifting focus and preventing access to the page until closed; use sparingly to avoid disruption.

Syntax:

alert("Your message goes here");

Parameters: message: The text to display in the alert box.

Return Value: none

Example: To demonstrate triggering an alert using JavaScript after a delay.

JavaScript
setTimeout(() => {
  alert("Hello, this is an alert!");
}, 3000); 

Output:

Simple Alert box using JavaScript

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.

JavaScript
let userName = "John";
setTimeout(() => {
  alert("Hello, " + userName + "! Welcome to our website.");
}, 3000)

Output

Dynamic alert in JavaScript

Supported Browsers



Contact Us