Last Updated : Jul 1, 2023
This built-in method allows us to display a dialog box with a message and an input field to the user.
The message serves as a prompt, guiding the user on what type of input is expected.
The user can then enter their response in the input field and submit it by clicking "OK" or pressing Enter.
The prompt() method captures the user's input as a string value, which we can store in a variable for further processing.
By leveraging the prompt() method, we can create interactive console applications that engage users and make our programs more dynamic.
// Prompt the user for input let userInput = prompt('Please enter your name:'); // Process the user's input console.log('Hello, ' + userInput + '!');
- We start by calling the prompt() method and passing in a string message as a parameter. This message serves as a prompt or instructions to the user, indicating what type of input is expected.
- The prompt() method displays a dialog box with an input field, allowing the user to enter their response. In this example, we are asking the user to enter their name.
- The user enters their input in the input field and clicks "OK" or presses Enter to submit their response.
- The value entered by the user is stored in the userInput variable. We can now use this variable to access and manipulate the user's input.
- In this case, we concatenate the user's input with the string 'Hello, ' and the exclamation mark '!'. We then log this greeting message to the console using the console.log() function.
- When you run this code, the console will display the message "Please enter your name:" as a prompt. After the user enters their name and submits it, the console will log the greeting message with the user's name.
User input is vital for creating interactive console applications that can respond dynamically to user actions.
The prompt() method provides a simple and convenient way to obtain user input and utilize it within your code.
With the knowledge gained from this tutorial, you are now equipped to create more engaging and user-friendly console applications that involve user input.
Remember to explore additional input validation and error handling techniques to create robust and user-friendly programs.