Skip to main content
X

Explore your training options in 10 minutes

JavaScript Tutorials

JavaScript alert() Method

Ryan Manchester - January 12, 2021


The JavaScript alert() method, also known as Window.alert() , displays an alert dialog box to a user. It accepts an optional message argument to display a message with an OK button to the user. Common uses for alert() are to let the user know an action was successful, or to display errors.

The alert() method also comes in handy as a development tool. For example, placing an alert() inside a function to handle a form submission. Commonly, the alert() will be placed after event.preventDefault() is called.

For review, event.preventDefault() simply cancels the default behavior of redirecting after the submit button is clicked. Read this quick tutorial to further review event.preventDefault() .

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses










By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

What is JavaScript alert()?

JavaScript alert() displays a pop-up dialog box. An optional message in the form of a string can be passed in to display a custom message. An important note about alert() is it should only be used to display a message that requires acknowledgement by clicking OK. A message requiring an action should not utilize alert() .

An alert() dialog box has many uses. It can be used to display success or errors in the context of a fetch() request. Another use is to display alert() in a function to ensure the program is appropriately flowing.

alert() JavaScript Syntax

The syntax for alert() is concise and straightforward. Simply invoke alert() with a message in the form of a string:

alert('message')

This would display a dialog box that would say ‘message.’ Place your custom message as a string to display it.

The message is optional. If a message is not included, a blank dialog box with an OK button appears.

alert()

JavaScript alert() Examples

In the introduction of this article, we considered a user and a developer scenario for using alert() . Let’s now take a look at how each one would be implemented. Let’s start with the developer side. We will put an alert() inside of a function that handles form submission.

We will start with a basic form for logging in with a username and password.

<form>
<label>Name</label>
<input type="text" name="name">
<label>Password</label>
<input type="text" name="name">
<button type="submit">
Log In
</button>
</form>

Which renders:

Now let’s build a function to pass to the onSubmit property of our JavaScript form.

const handleOnSubmit = (event) => {
 event.preventDefault();
 alert("Logged In")
}

Then we pass this function to our form in the onSubmit property.

<form onSubmit="handleOnSubmit(event)">
<label>Name</label>
<input type="text" name="name">
<label>Password</label>
<input type="text" name="name">
<button type="submit">
Log In
</button>
</form>

Now we can click on the Login button to see if we’ve wired the function to the form properly. After clicking the button we get a dialog box that looks like this:

Venus, a software engineer at Rockbot

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Great! We know that our function we defined is communicating with our form. JavaScript alert() gives us a simple way to check the flow of our program.

For our next example, let’s take a look at how we can expose success and error messages in a fetch() request.

fetch('/current-cart/', {
      credentials: 'include',
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
    })
    .then(resp => resp.json())
    .then(cart => {
      if(cart.error){
        alert(cart.error)
      }

In this example, we have a shopping cart fetch request in an e-commerce app. We are sending a request to see if a current shopping cart has been stored. Going through the request to the end, we have an alert() that will display errors, if any.

Since there is not an active shopping cart we get this error:

This example is more useful in development than production, but the same principles can be applied as validations on a form for example.

return fetch('/login', {
      credentials: 'include',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(creds)
    })
    .then(resp => resp.json())
    .then(response => {
      if (response.error) {
        alert(response.error)
      }

Here, the alert() will display the error messages associated with a log-in form. If a user tries to log-in without filling in the form, we get these errors:

This is an example of directing the user experience using alert() to display validations.

We’ve seen how alert() can be used both development side and client side — what the user sees. Let’s take a moment to recap what we’ve learned.

Conclusion

JavaScript alert() is a simple method that has many broad uses. It takes an optional argument of a message as a string data type. It displays a dialog box with the message and an OK button. Remember that alert() is only meant to display messages and is not able to take any actions.

In our examples, we saw how alert() can be used in development to track the communication of a function and a form. Then, we saw how alert() can expose error messages in the development side of a fetch request. In our final example, we saw how alert() can be used to deliver validation errors in a form to a user.

By now, you should have a grasp on common uses for alert() . Try it out in your next JavaScript project as a way to test different functionalities.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

What's Next?

Ryan Manchester

About the author: Ryan is a technical writer at Career Karma, where he covers programming languages, technology, and web development. The Texas native earned his Bachelor's of Music Composition from the University of North Texas. Ryan is currently pursuing further education in web development, aiming to graduate from Flatiron School with a certification in full stack web development. Since joining the Career Karma team in November 2020, Ryan has used his expertise to cover topics like React and Ruby on Rails.

Previous Article

What is a Binary File?

Next Article

How to Exit Vim

Skip to main content