prompt() function in javascript

  • The prompt() function is a built-in function in JavaScript that allows the developer to interact with the user and get input from them through a pop-up dialog box. The prompt() function displays a message to the user and asks for their input. The input is returned as a string.
The syntax for the prompt() function is as follows:


    prompt(message, defaultInput);

  • The message parameter is a string that represents the message that will be displayed to the user in the dialog box. This message is usually used to ask the user for some input.
  • The defaultInput parameter is an optional parameter that represents the default value that will be displayed in the input box. If this parameter is omitted, the input box will be empty.
  • When the prompt() function is called, it will display a dialog box to the user that includes the message specified in the message parameter and an input box where the user can enter their input. If the user clicks the "OK" button, the input will be returned as a string. If the user clicks the "Cancel" button, the function will return null.
Here is an example of how the prompt() function can be used:


    let name = prompt("What is your name?", "John Doe");
    if (name !== null) {
        console.log("Hello " + name + "!");
    } else {
        console.log("User cancelled the prompt.");
    }


  • In this example, the prompt() function is used to ask the user for their name. If the user enters a name and clicks "OK", the name variable will be set to the input value, and the program will print a greeting to the console. If the user clicks "Cancel", the prompt() function will return null, and the program will print a message indicating that the user cancelled the prompt.

No comments:

Post a Comment