JavaScript Simple Actions: alert(), prompt(), and confirm()

JavaScript Simple Actions: alert(), prompt(), and confirm()

JavaScript Simple Actions: alert(), prompt(), and confirm()

JavaScript provides three built-in dialog functions for user interaction:

  1. alert() – Displays a simple message.
  2. prompt() – Asks for user input.
  3. confirm() – Requests confirmation (OK/Cancel).

šŸ”¹ 1. alert() – Display a Message

The alert() function shows a popup message with an "OK" button. It is commonly used to show notifications or warnings.

Example:

alert("Welcome to JavaScript!");

šŸ›  Output:
A pop-up box with "Welcome to JavaScript!" and an OK button.

šŸ”¹ 2. prompt() – Ask for User Input

The prompt() function displays a dialog box asking the user to enter some text.
It returns:
✅ The text entered by the user.
null if the user clicks Cancel.

Example:

let name = prompt("What is your name?"); alert("Hello, " + name + "!");

šŸ›  Output:

  1. A pop-up appears: "What is your name?" with a text box.
  2. If the user types "John" and clicks OK, the next alert will show:
    šŸ‘‰ "Hello, John!"

Example with Default Value:

let age = prompt("Enter your age:", "18"); // Default value is 18 alert("Your age is " + age);

šŸ›  Output:
If the user doesn't change "18" and presses OK, it will show:
šŸ‘‰ "Your age is 18"

šŸ”¹ 3. confirm() – Ask for Confirmation

The confirm() function asks the user to confirm an action.
It returns:
true if the user clicks OK.
false if the user clicks Cancel.

Example:

let result = confirm("Are you sure you want to delete?"); if (result) { alert("Item deleted!"); } else { alert("Action canceled."); }

šŸ›  Output:

  1. A dialog box appears with: "Are you sure you want to delete?"
  2. If the user clicks OK, it shows "Item deleted!"
  3. If the user clicks Cancel, it shows "Action canceled."

šŸ”¹ Summary Table

FunctionPurposeReturns
alert("Message")Displays a messageNothing (undefined)
prompt("Message")Asks for inputString (null if canceled)
confirm("Message")Asks for confirmationtrue (OK) / false (Cancel)

šŸš€ Use Cases

  • alert() → Show simple notifications.
  • prompt() → Get user input before proceeding.
  • confirm() → Confirm before performing critical actions.

šŸŽÆ Practice using these methods to enhance user interaction in your JavaScript projects! 

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close