In this blog post, we will explore how to use the prompt() API provided by web browsers. This API allows us to prompt the user for input, making it useful for various scenarios.

The prompt() API has been around since the early days of the web and is supported by all browsers. It provides a simple way to gather user input without the need to set up a form. This can be particularly handy when prototyping an application.

To use the prompt() function, simply call it and pass a string that represents the question you want to ask the user. For example:

prompt("How old are you?");

This will display a prompt dialog box to the user, where they can enter their response. The appearance of this dialog may vary slightly depending on the browser being used.

Once the user enters their input and clicks either the OK or Cancel button, the script execution is blocked until the user takes action. The value entered by the user is then returned from the prompt() function. You can assign this value to a variable, as shown below:

const age = prompt("How old are you?");

It is also possible to provide a default value that will be pre-filled in the prompt. This can be useful when you want to suggest a value to the user. Simply pass the default value as the second parameter to the prompt() function, like this:

const age = prompt("How old are you?", 18);

If the user clicks the OK button without entering anything, an empty string will be returned. If the user clicks the Cancel button, the prompt() function call will return null.

In summary, the window.prompt() API provides a straightforward way to gather user input through a dialog box. It is a useful tool for quickly obtaining information from the user, especially during the prototyping phase of an application.

Tags: JavaScript, web development, user input, prompt API