JavaScript prompt()
Published Jun 2, 2023Updated Feb 20, 2025
Contribute to Docs
The prompt() function is a built-in JavaScript method that displays a modal dialogue box prompting the user for input. It is part of the Web API, provided by the browser’s window object, and pauses script execution until the user responds. The function returns the user’s input as a string or null if the user cancels the dialogue.
Syntax
The prompt() function accepts two parameters and returns a string or null:
prompt(message)
or, alternatively
prompt(message, defaultValue)
message: A string that will be displayed in the dialog box.defaultValue(Optional): A default value pre-filled in the input field.
The function returns:
- The user’s input as a string.
Nullif the user clicks “Cancel” or closes the dialog.
Example
This example demonstrates how to use the prompt() function to get user input:
let name = prompt('Please enter your name:');if (name !== null) {console.log('Hello, ' + name + '!');} else {console.log("You didn't enter a name.");}
A greeting displaying that name appears when a name is entered and OK is clicked. If Cancel is clicked, a message indicating that no name was entered is shown.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours