Alerts And Prompt In Javascript

Posted on December 15, 2024 by Vishesh Namdev
Python C C++ Javascript Java
Alerts and Prompt in JS

Alerts and Prompt
Alerts are used to display messages to the user. They can be used to display success messages, error messages, or warnings.
Prompts are used to get user input. They can be used to get a value from user.

Alert Method

The alert method displays a popup box with a message and an "OK" button. It is often used to show information or a simple warning.
Syntax

alert(message);

Example

alert("Hello! This is an alert message.");

Prompt Method

The prompt method displays a popup box that asks the user for input. It includes a text box and "OK" and "Cancel" buttons. It returns the input entered by the user as a string, or null if the user cancels.
Syntax

prompt(message, defaultValue);

  • message: A string that explains what input is expected.
  • defaultValue (optional): A string that pre-fills the input field.
  • Example

    let name = prompt("What is your name?", "Guest");
          if (name !== null) {
              alert("Hello, " + name + "!");
          } else {
              alert("You cancelled the prompt.");
          }