How to Use prompt() in JavaScript: Syntax and Examples
In JavaScript, use the
prompt() function to display a dialog box that asks the user for input. It returns the text entered by the user as a string or null if canceled.Syntax
The prompt() function shows a dialog box with an optional message and a text input field. It returns the user's input as a string or null if the user clicks cancel.
message: A string to display as the prompt message (optional).- Returns: The text entered by the user or
null.
javascript
let userInput = prompt(message);Example
This example asks the user for their name and then shows a greeting using the input.
javascript
const name = prompt('What is your name?'); if (name !== null && name !== '') { alert('Hello, ' + name + '!'); } else { alert('No name entered.'); }
Output
A prompt dialog appears asking "What is your name?". If the user types "Alice", an alert shows "Hello, Alice!". If canceled or empty, it shows "No name entered."
Common Pitfalls
Some common mistakes when using prompt() include:
- Not checking if the user pressed cancel (which returns
null). - Assuming the input is always a string with content (it can be empty).
- Using
prompt()in environments where it is not supported (like some browsers or Node.js).
javascript
/* Wrong way: Not checking for cancel or empty input */ const input = prompt('Enter a number:'); const number = Number(input); alert('You entered: ' + number); /* Right way: Check for cancel and empty input */ const inputSafe = prompt('Enter a number:'); if (inputSafe !== null && inputSafe.trim() !== '') { const numberSafe = Number(inputSafe); alert('You entered: ' + numberSafe); } else { alert('No valid input entered.'); }
Quick Reference
Remember these tips when using prompt():
- It pauses script execution until the user responds.
- Returns
nullif canceled. - Always validate user input before using it.
- Works only in browsers, not in Node.js.
Key Takeaways
Use
prompt() to get user input as a string in browsers.Always check if the user pressed cancel (returns
null) before using input.Validate and handle empty or unexpected input to avoid errors.
prompt() pauses code execution until the user responds.It works only in browser environments, not in server-side JavaScript.