Javascript alert, confirm, prompt method

Learn how to use alert, confirm and prompt in javascript.

Javascript has three different popup boxes which can be used accordingly.

Javascript Alert

window.alert(message) is used to notify end user with a message. It has Ok button which needs to pressed in order to proceed further.

alert('You are about to reload the site!');

It can be declared with window object.


Javascript Confirm

window.confirm(message) is used to get a confirmation from the end user in order to proceed further.

It has a Ok button which returns true when pressed and a cancel button which returns false when selected.

const proceed = confirm('Are you sure you want to delete this item');
if(proceed){
  console.log('Yes you can delete the item');
}else{
  console.log('No you can delete the item');
}

It can also be declared with window object.


Javascript Prompt

window.prompt(message, defaultValue) is used to get some information is needed from the end user in order to proceed further.

It has Ok button which returns input value when pressed and cancel button which returns null when selected.

It takes two parameters as input

  1. Question: Required.
  2. Default Value: Optional.
const proceed = prompt('Are you sure you want to delete this item', "No");

if(proceed){
  console.log(proceed);
}else{
  console.log('You have not provided a answer');
}

It can also be declared with window object.

Javascript alert, confirm & prompt are styled default to browser and you cannot change the default button text or style.

Check this out if you want to create custom popup boxes.

Leave a Reply

Your email address will not be published. Required fields are marked *