Alert, prompt, confirm in JavaScript

May 28, 2020

In this article, we will learn about the browser functions alert, prompt, and confirm.

Photo by [Artem Sapegin](https://unsplash.com/@sapegin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/javascript?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)Photo by Artem Sapegin on Unsplash

Alert 🚨

alert → It displays a message in an alert box with an ok button. While displaying the alert box, the script execution is paused until the user presses “OK” or “ESC” key.

Syntax

alert(message)

Example

alert("This is a alert 🚨");

You can also pass any javascript statement.

alert(2+4);

Calling a function

function getMessage() {

    return "Hi 👋 from Javascript Jeep ";
}

alert(getMessage())

To display a line break you can use

alert("Hello from /n JavaScript Jeep");

prompt

The prompt method requests the user to input a value by displaying a dialog with ok and cancel button. Script execution is paused until the user presses “OK” or “Cancel”

Syntax

let returnValue = prompt(message, [default_value]);

message → The title to display in the dialog box.

default_value → The default (initial) value set in the input box. It is an optional argument in all browsers except, Internet Explorer. In IE if we don’t pass the default, it will insert the text "undefined" into the prompt.

The call to prompt returns the text from the input field or null if the input was canceled.

const YOB = prompt("What is your Year of Birth?", '');

If the user enters a value and press “OK”, then the value stored in age is user input. If the user clicks the “Cancel” button or “Esc” key, then the value of age is null

let YOB = prompt('What is your Year of Birth?', 1900);

const currentYear = new Date().getFullYear();

if(YOB === null) {
    YOB = 1900
}

alert(`You are ${currentYear - YOB} years old!`); // You are 100 years old!

confirm

The confirm method will display a confirm box displaying a message (usually a question) with ok and cancel button .

Syntax

let isConfirmed = confirm(question);

The confirm method returns true if OK is pressed and false otherwise.

Example

let canDelete = confirm("Do you want to delete the file ? ");

Conclusion

All these methods pause the script execution and don’t allow the user to interact with the rest of the page until the window is closed.

The location and style of the dialog is not customizable.

Please, donate me here. Even a small penny is huge to me