How to use the alert() method in JavaScript

Alerts in Javascript are dialogue boxes that appear to the user when something important is to be conveyed, just like in real life.

For example, when an alert window pops up, the user has to close it manually in order to proceed with their work.

Do you want to say something important?
1 of 3

Is an alert always serious?

Alerts can be used in multiple ways:

  • The most common alert we see is everytime we close a document and we are asked “Do you want to save this document?” This is an example of alert. As the alert box must be closed manually it can prove to be quite useful at times like these.
  • Sometimes when you require certain fields in a google form you can add alerts if the user tries to submit the form, leaving that field empty.
  • Alerts can also be used to give users warnings, like when you open a website and a message pops up that says “This website uses cookies!”.

Hence, alerts are a useful tool to learn!

Understanding alerts through code

1. Alerts using buttons

You can create a button that will display an alert message when clicked. The example below shows you how to do this.

  • HTML

2. Alerts before the page is loaded

An alert message can simply be shown when the HTML file runs, before the user accesses any other elements on the page. The example below shows how to do this.

  • HTML

In the above snippet, the alert method is called in the head section of the HTML file as this allows the message to be shown before the rest of the page is visible. Note that without a button, the alert code is written within the <script> tags.

3. Alerts using variables

Alerts dont just show text values. They can also be used to show variable values created within the file. The code example below shows how this is done.

Note that in the snippet below, when passing a variable to the alert method, you are not required to put the variable name in “double quotes”. This signifies that the value given to the alert method is a variable.

As you can see in the below code, from line 4 to 8, we can even put alert messages in methods and call them when needed. This way the same message can be shown in multiple places without having to re-write the code.

  • HTML
Copyright ©2024 Educative, Inc. All rights reserved