Understanding and Using the prompt Function in JavaScript

The prompt function is a simple way to interact with users in JavaScript. We explore how to use prompt, its syntax, and provides examples of its use.

Syntax of prompt

The basic syntax of prompt is as follows:


let response = prompt(message, default);
            
  • message: A string of text to display to the user.
  • default: A default string to display in the prompt input field.

Using prompt

To use the prompt function, simply call it with the required parameters. Here’s a basic example:


let userName = prompt("Please enter your name", "javascriptux friend");
if(userName) {
    alert("Welcome, " + userName + "!");
}
            

This will display a dialog box with the message “Please enter your name” and a default input value of “javascriptux friend”.

Practical Uses of prompt

The prompt() function can be used in various scenarios, such as:

  • Collecting user input before proceeding with a script.
  • Quickly creating interactive scripts for user feedback.
  • Debugging or testing code with manual input.

Leave a Reply

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