JavaScript alert()/window.alert(): Alert Dialog Box

Assume you're browsing a website when a popup appears with a message that piques your interest. That is the power of JavaScript's alert() function! This straightforward but powerful function can be used to add eye-catching messages, prompts, and warnings to your web pages. So let's describe this function, starting with its brief definition.

The alert dialog box with an optional message and an OK button is displayed using the JavaScript alert() method. The alert dialog box disappears after the user clicks the OK button.

JavaScript alert() syntax

The syntax of the alert() method in JavaScript is:

alert(message)

The message is optional and is used to display some information to the user regarding the alert box.

JavaScript alert() example

Consider the following code as an example demonstrating the alert() method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <h2>The alert() Method</h2>
   <button onclick="myFunction()">Click Me to Alert</button>
   <script>
      function myFunction() {
         alert("Hi there!");
      }
   </script>
   
</body>
</html>
Output

The alert() Method

It should be noted that alert() is the same as window.alert(). It is because window is a global object. And in JavaScript, a method by default belongs to the window  object.

Advantages of the alert() function in JavaScript

Disadvantages of the alert() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!