Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 4 - Basic Interaction

4.2 Prompt

The prompt method in JavaScript is used to display a dialog box with a message, an input field for the user to enter data, and OK and Cancel buttons. Here's how you can use it to take user input:

let name = prompt("Enter your name:");
console.log("Hello, " + name + "!");

When you run this code:

  1. A dialog box will appear with the message "Enter your name:" and an input field.
  2. The user can type their name into the input field and then click OK.
  3. The value entered by the user (the name) will be stored in the variable name.
  4. The script will then log a message to the console, greeting the user with their entered name.

If the user clicks Cancel or leaves the input field blank and clicks OK, the prompt method will return null. It's important to handle this case if the input is required.

This method is commonly used when you need to gather user input interactively, such as asking for a name, age, or any other information that the user can provide through text input.