DEV Community

Cover image for JavaScript alert, prompt, and confirm
Bello Osagie
Bello Osagie

Posted on • Updated on

JavaScript alert, prompt, and confirm

alert

The alert function accepts a single argument. It displays the result on a modal dialog window.

The word "modal" means a user can't interact with the rest of the page.

The modal dialog window is a small box displayed on a web page.

Syntax:

alert(arg);
Enter fullscreen mode Exit fullscreen mode
alert('Hello World!');
Enter fullscreen mode Exit fullscreen mode

prompt

The prompt function accepts two arguments.

Syntax:

prompt(arg1[, arg2]);
Enter fullscreen mode Exit fullscreen mode
  • arg1 is required.
  • arg2 is optional.

On Internet Explorer, arg2 is required.

// For other browsers
const birthYear = prompt("What year were you born?");
alert(birthYear);

// For Internet Explorer
const yourName = prompt("What is your name?", "Michelle");
alert(yourName); 
Enter fullscreen mode Exit fullscreen mode

confirm

The confirm function only accepts an argument.

Syntax:

confirm(arg);
Enter fullscreen mode Exit fullscreen mode

If OK is clicked, the result is true and false otherwise.

const isDoctor = confirm("Are you a Doctor?");
alert(isDoctor); // true if OK button is clicked
Enter fullscreen mode Exit fullscreen mode

The above example is the same as below:

const isDoctor = prompt("Are you a Doctor?");
// const isDoctor = prompt("Are you a Doctor?", 'y/n'); IE

if (isDoctor === 'y') {
  alert("true");
} else if (isDoctor === 'n') {
  alert("false");
} else {
  alert("enter either y/n")
}  
Enter fullscreen mode Exit fullscreen mode


Buy me a Coffee


TechStack Media | Bluehost

  • Get a website with a free domain name for 1st year and a free SSL certificate.
  • 1-click WordPress install and 24/7 support.
  • Starting at $3.95/month.
  • 30-Day Money-Back Guarantee.

Top comments (0)