JavaScript alert, prompt, and confirm

JavaScript alert, prompt, and confirm

·

2 min read



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);
alert('Hello World!');

prompt

The prompt function accepts two arguments.

Syntax:

prompt(arg1[, arg2]);
  • 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);

confirm

The confirm function only accepts an argument.

Syntax:

confirm(arg);

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

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")
}

Buy me a Coffee


TechStack | 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.