javascript

prompt() method

Learn how the JavaScript `prompt()` method gets text input from a user in the browser. Understand its return values, default options, and how to use it in simple web projects.

9 min read 8 sections Tutorial
Share

The `prompt()` method is a way to ask the user a question and get a text answer back. It creates a small pop-up window in the web browser where the user can type something. This method is part of the browser's way to interact with visitors. It's useful for simple inputs like asking for a name or a number.

prompt() method

prompt() method

The prompt() method shows a dialog box that asks the user for input. This box has a message, an input field where the user types, and "OK" and "Cancel" buttons.

When the user types something and clicks "OK", prompt() gives you back what they typed. If they click "Cancel", it gives you a special value called null.

It's important to remember that prompt() only works inside a web browser. It does not work in other JavaScript environments like Node.js.

What is prompt()?

The prompt() method displays a dialog box that asks the user for text input. It returns the text the user entered or null if the user cancels the dialog.

Gets User Input

It opens a small window for the user to type text into.

Returns a String

Whatever the user types, it always comes back as text (a string).

Optional Default

You can provide text that already fills the input field for the user.

Browser Only

This method only works when your JavaScript runs in a web browser.

How to Use prompt()

Getting Started

How to Use prompt()

Using prompt() is very simple. You just call the method and give it a message. This message is the question you want to ask the user.

The value that the user types is then stored in a variable. You can then use this variable in your program.

Remember, the dialog box stops all other JavaScript code until the user clicks "OK" or "Cancel".

JS · Browser
1// Call prompt() with a message to ask the user a question
2let userName = prompt('What is your name?');
3
4// Check if the user typed something or canceled
5if (userName !== null && userName !== '') {
6 // If they typed a name, say hello
7 console.log('Hello, ' + userName + '!');
8} else {
9 // If they canceled or typed nothing, say goodbye
10 console.log('No name provided. Goodbye!');
11}

prompt() always returns a string

Even if the user types a number, prompt() gives you back text. For example, if they type 50, you get the string '50', not the number 50. If you need a number, you must convert it yourself using Number() or parseInt().

Understanding prompt()'s Return Value

Understanding prompt()'s Return Value

The value you get back from prompt() changes based on what the user does. If the user types text and clicks "OK", you get that text as a string.

If the user clicks "Cancel", you get the special value null. null means "no value" or "nothing here". Your code should always check for null to know if the user canceled.

If the user clicks "OK" without typing anything, you get an empty string ('').

JS · Browser
1// Ask the user for their favorite number
2let favNumberInput = prompt('What is your favorite number?');
3
4// Check if the user canceled (favNumberInput will be null)
5if (favNumberInput === null) {
6 console.log('You canceled the prompt!');
7} else if (favNumberInput === '') {
8 // Check if the user clicked OK but typed nothing
9 console.log('You didn\'t enter a number.');
10} else {
11 // If they typed something, try to convert it to a number
12 let favNumber = Number(favNumberInput);
13
14 // Check if the conversion was successful
15 if (isNaN(favNumber)) {
16 console.log('That\'s not a valid number!');
17 } else {
18 console.log('Your favorite number is: ' + favNumber);
19 }
20}
✗ BadWrong — Not converting to number
let ageString = prompt('How old are you?');
// If user types '10', ageString is '10'
let nextYearAge = ageString + 1;
// This will be '101', not 11, because '10' + 1 is string concatenation
console.log(nextYearAge);
✓ GoodCorrect — Converting to number
let ageString = prompt('How old are you?');
// Always check for null first
if (ageString !== null) {
let age = Number(ageString);
// Now if user types '10', age is the number 10
let nextYearAge = age + 1;
// This will correctly be 11
console.log(nextYearAge);
} else {
console.log('Age not provided.');
}

Adding a Default Value

Adding a Default Value

You can make prompt() even more helpful by giving it a second piece of information. This second piece is a default value. The default value shows up pre-filled in the input box.

This is useful when you want to suggest an answer or provide the most common choice. The user can then just click "OK" to accept the default, or type their own answer.

Without Default Value
// The input box starts empty
let city = prompt('Which city do you live in?');
console.log('City:', city);
VS
With Default Value
// The input box starts with 'New York'
let city = prompt('Which city do you live in?', 'New York');
console.log('City:', city);

When to use a default value

Use a default value when you want to guide the user or save them typing. For example, if most users live in 'London', you can set 'London' as the default. This makes your website easier to use.

Building a Simple Interactive Tool

Building a Simple Interactive Tool

Let's see how prompt() can be used to build a tiny interactive tool. We can ask for a user's name and age, then use that information to create a personalized message. This shows how to combine prompt() with variables and basic logic.

This simple example demonstrates a common pattern: getting input, processing it, and then showing a result.

1

Get the user's name

First, use prompt() to ask for the user's name. Store this in a userName variable.

javascript
1let userName = prompt('Please enter your name:');
2

Get the user's age and convert it

Next, ask for their age. Remember that prompt() returns a string, so convert it to a number using Number().

javascript
1let ageInput = prompt('How old are you?');
2let age = null; // Default to null if not provided or invalid
3
4if (ageInput !== null && ageInput !== '') {
5 age = Number(ageInput);
6}
3

Create and display a personalized message

Now, combine the name and age to create a greeting. Check if both were provided before showing the message.

javascript
1if (userName && age !== null && !isNaN(age)) {
2 console.log('Hello, ' + userName + '! You are ' + age + ' years old.');
3} else if (userName) {
4 console.log('Hello, ' + userName + '! We couldn\'t get your age.');
5} else {
6 console.log('Welcome, guest!');
7}

prompt() blocks the page and is for browsers only

The prompt() dialog stops your JavaScript code from running until the user responds. This can make your web page feel slow. Also, prompt() is a browser feature. If you try to use it in a Node.js script, it will cause an error because Node.js does not have a browser window.

prompt() Method Details

prompt() Method Details

ParameterTypeDescription
messagestringThe text to display in the dialog box, asking the user a question.
defaultValue (optional)stringA default string to show in the input field. If omitted, the field is empty.

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What does prompt('Enter your age:') return if the user types 25 and clicks OK?

Quick Check

What does prompt('Are you ready?') return if the user clicks 'Cancel'?

Quick Check

Which of these is the correct way to use prompt() with a default value?

Quick Check

Where can the prompt() method be used?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Purposeprompt() shows a dialog box to get text input from the user.
  • 2Returns String — The value returned by prompt() is always a string, even if it looks like a number.
  • 3Returns null — If the user clicks the "Cancel" button, prompt() returns null.
  • 4Returns Empty String — If the user clicks "OK" without typing anything, prompt() returns '' (an empty string).
  • 5Optional Default — You can provide a second argument, a string, to set a default value in the input field. Example: prompt('What?', 'Default').
  • 6Browser-Onlyprompt() works only in web browsers, not in Node.js or other environments.
  • 7Blocking — The dialog box stops all other JavaScript code until the user responds.
  • 8Type Conversion — If you need a number, use Number() or parseInt() to convert the string input.
  • 9Check for null/empty — Always check if the return value is null or '' to handle user cancellation or empty input gracefully.
  • 10Modern Alternatives — For better user experience, use HTML forms (<input> elements) instead of prompt() in real web applications.

alert() method

Learn about alert() to show simple messages to the user without expecting input.

confirm() method

Explore confirm() to ask the user a yes/no question.

HTML Forms

Understand how to build better user input fields using HTML and JavaScript.

Input Validation

Learn how to check if user input is correct and safe to use.

You now understand the JavaScript prompt() method!

You've learned how to use prompt() to get text from a user, how to handle different return values, and when to use default options. You also know its limitations and what modern alternatives exist for user input in web development.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning