Open In App

How to Create an Alert in JavaScript ?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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

Output:

alertJS

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

JSalert

Dynamic alert in JavaScript


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads