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.

Issue with types

Note that the prompt function always returns a string, even if the user entered a number. For example, consider the following script:

let num1 = prompt('Enter the first number'); let num2 = prompt('Enter the second number'); alert(num1 + num2); // concatenates numbers like strings

Modify the above code so that numbers are summed not like strings.

Use the prompt function to ask the user for the side of a square. Display the area of the given square.

Use the two functions prompt to ask the user for the sides of a rectangle. Display the perimeter of the given rectangle.