How to use the alert() Function in JavaScript

A JavaScript alert is a message dialogue box that appears above a page in the browser window. Their main purpose is to highlight an important message to the user since the user must click "OK" to confirm the message before continuing to use the page.


In this tutorial, we will learn how to create alerts in JavaScript.


JavaScript alert() Syntax

The alert() function accepts one optional argument; the message to display.




Alert on Page Load

The most basic way to use the alert() function is to call it outside of any other code in your JavaScript resulting in it being called on page load.




Here is another example, but with implementation from within the HTML page:




Alert on Button Click

In the example below, we will send an alert when a button with an ID is clicked.


<button id="btn">Click me</button>
document.getElementById('btn').addEventListener('click', function() {


Alert with Dynamic Message

To display a dynamic alert message, supply a variable with the message string to alert()


document.getElementById('btn').addEventListener('click', function() {
  var msg = 'Hello';