How to Prompt the User for Input in JavaScript

By Chris Minnick, Eva Holland

One way to ask a user for data is by using the JavaScript prompt command. To try out the prompt command, open the JavaScript console and type the following:

prompt("What is your name?");

After you press Return or Enter, a pop‐up window appears in your browser window with a text field, as shown here.

Prompting the user for input.

Prompting the user for input.

After you enter your name and click OK, the pop‐up window ­disappears, and the value that you entered in the pop‐up displays in the console, as shown here.

Displaying your name.

Displaying your name.

That’s all well and good if all you want to do is capture data and immediately repeat it back like a parrot. But what if you want to do something with the user‐entered data? To do that, you need to store it in a variable.

To store user‐entered data in a variable, you create a new variable and then follow it with =. You then follow it with the prompt statement.

var username = prompt("What is your name?");

It’s important to note that a single equal sign (=) in JavaScript is called the assignment operator. Its job is to put the value on the right into the variable on the left.

When you press Return or Enter, a pop‐up window appears in your browser, just as before.

When you enter your name in the pop‐up window and click OK, the JavaScript Console prints out undefined, indicating that the statement is finished and there’s nothing else for it to do.

To see the value you just entered, you can type the variable name into the console. JavaScript responds with the value of the variable, as shown here.

Getting the value of a variable from a prompt.

Getting the value of a variable from a prompt.