learn2kode.in

JavaScript Alert, Prompt, and Confirm

JavaScript provides built-in dialog boxes that allow developers to interact with users directly through the browser. The three most commonly used dialog methods are alert(), prompt(), and confirm(). These methods are part of the Window Object and are widely used for notifications, confirmations, and simple user input.
The window object controls the browser itself.

1. JavaScript alert()

The alert() method displays a simple message box with an OK button. It is mainly used to show information or warnings to users.

Example

alert("Welcome to Learn2Kode!");

Key Points

2. JavaScript prompt()

The prompt() method displays a dialog box that asks the user for input. It includes a text field along with OK and Cancel buttons.
let name = prompt("Enter your name:");
console.log(name);

How It Works

3. JavaScript confirm()

The confirm() method displays a dialog box with OK and Cancel options. It is commonly used for confirmations before performing actions.
let isConfirmed = confirm("Do you want to continue?");
if (isConfirmed) {
  console.log("User agreed");
} else {
  console.log("User cancelled");
}

Return Values

Comparison Table

Method Purpose User Action Return Value
alert() Show message OK None
prompt() Get user input OK / Cancel String / null
confirm() Get confirmation OK / Cancel true / false

Best Practices

Real-World Use Cases