JavaScript alert() Tutorial

In this section, we will learn what window alert() method is and how to use it in JavaScript.

JavaScript Window alert() Method

The `alert()` method is used to show a message to users via a dialog box (which has only an OK button in it).

This method is typically used when users must be made aware of something that they have no control over, such as an error.

Notes:

  • The dialog that will appear to the user is synchronous. This means code execution stops when a dialog is displayed, and resumes after it has been dismissed.
  • Also, the shape of this dialog is system dependent and we can’t change it via CSS.

Window alert() Method Syntax:

alert(message)

Window alert() Method Parameter:

The method takes one argument and that is the message (String value) that we want users to see.

Window alert() Method Return Value:

The method does not return a value.

Example: using Window alert() method in JavaScript

console.log("Start");

alert("Hello");

console.log("End");

In this program, first the message `Start` will appear on the console and after that a dialog with the message `Hello` pops up. At this time, as long as we don’t dismiss this dialog, the rest of the program (including the rendering of the content on the page) will stop. So we need to be careful about when to use the `alert()` function.

Example: alert box in JavaScript

console.log("Start");

alert("Welcome to My page:) ");

console.log("End");

Example: message box in JavaScript

setTimeout(()=>{

alert("This message appeared after 5 seconds!");

},5000)

JavaScript alert() with Yes No

The short answer is that you can’t have an alert() function with Yes or No buttons! To create such a dialog box, there’s another function called confirm(). You can learn about this function in the next section.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies