To ask user input in JavaScript, use the built-in window.prompt() method.
For example:
window.prompt("Enter your name");
This shows the following modal at the top of your page:

Prompt Box in JavaScript
To ask for user input in JavaScript, you can use the built-in prompt box. To show a prompt, use the prompt() method.
This method takes two arguments:
- Message. The message that asks the user for the input.
- Default input. The default input value before user types anything. This is an optional argument.
The prompt() method returns the user input as a string. If no input is specified, it returns a null.
Here is an example of a prompt in JavaScript:
prompt("Enter your name:", "Alice");
When you run this piece of code, you get a prompt that looks like this:

How to Store User Input in JavaScript
If you ask for user input, you may also want to store it somewhere. To store the input, just assign it to a new variable.
For example:
var nickname = prompt("Enter a name you want to be called");
Now, when a user enters their name and clicks “OK” in the modal, their name will be stored into a variable called nickname.
For instance, let’s create a simple page that asks a user for a name and displays a greeting on the front page. Let’s create a file called index.html on the desktop and add the following HTML/JavaScript there:
<html> <head> </head> <body> <h1 id="welcome"> Hello! </h1> </body> <script type = "text/javascript"> var nickname = prompt("Please enter your name: "); if (nickname != null) { document.getElementById("welcome").innerText = "Hello, " + nickname + "!"; } </script> </html>
When you open up the index.html page, you are going to see a prompt at first:

When you enter a name into it, you are going to see the name appear on the front page:

And there you have it!
Conclusion
Today you learned how to ask user input in JavaScript.
To recap, you can ask user input with the built-in prompt() method. This opens up a prompt box where a user can enter text input. To store this input, assign the prompt into a variable.
Thanks for reading.
Happy coding!
Further Reading
100 JavaScript Interview Questions
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)
Python2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)
JavaScript2023.02.16JavaScript How to Get Selected Text from a Textbox
JavaScript2023.02.15JavaScript Select All Text in Div with a Mouse Click