Prompt function in JavaScript

You already know about the existence of the alert function that displays the given message on the screen. There is also a similar function prompt that allows you to get some text from the user.

Let's ask a user name as an example:

prompt('What is your name?');

Run the code above to see the window displayed by the prompt function. Type in your name and click the button. If you have done all the actions described above, then the name you entered will appear in our script.

In order to get access to the entered name, the result of the prompt function must be assigned to some variable, for example, like this:

let name = prompt('What is your name?');

Let's display the name entered earlier on the next line of the code using the function alert:

let name = prompt('What is your name?'); alert('Your name: ' + name);

You should understand that when calling the prompt function, further script execution is blocked until the appropriate data is entered. In general, the alert function works the same way, except it waits for the appropriate button to be pressed.

By the way, you don't have to use a variable:

alert('Your name: ' + prompt('What is your name?'));

Ask the user's age using the prompt function. Print user entered age with alert.