JavaScript How to Ask User for Input

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:

JavaScript prompt

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:

  1. Message. The message that asks the user for the input.
  2. 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:

JavaScript prompt

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:


    <h1 id="welcome"> Hello! </h1>  
  <script type = "text/javascript">
    var nickname = prompt("Please enter your name: ");

    if (nickname != null) {
      document.getElementById("welcome").innerText =
      "Hello, " + nickname + "!";

When you open up the index.html page, you are going to see a prompt at first:

javascript prompt that asks user a name

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

Hello HTML page

And there you have it!


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

50+ Web Development Buzzwords

100 JavaScript Interview Questions

About the Author

Artturi Jalli
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.