Syntax and Parameters
window.prompt() function has the following syntax where we have two parameters named
result = window.prompt(message, default);
- `result` is the value input by the user interactively
- `message` is the message which will be shown to the user with the input box
- `default` is the value which will be set to the input by default.
Display Message To The User
As stated previously we can display or present a message to the user during the input. We will use the message parameter. In this example, we will print the message
"Please Enter Your Age".
let age = prompt("Please Enter Your Age");
Different Ways To Call and Use prompt() Function
In the previous example, we have called
prompt() function directly. But there are different ways to call prompt() function those are described below. All of the following examples are the same and there is no difference.
prompt("Please Enter Your Age"); window.prompt("Please Enter Your Age");
Set Default Value Display Input Field
prompt() function is mainly used to input or get a value from the user. In some cases, we may need to specify a default value which can be used by the user. We can specify the default value after the message. In this example, we will use default value 18 for the age.
prompt("Please Enter Your Age","18");
Convert Input To Number
Cancel button the returned value will be
null which means there is no value. We can convert the inputted value into a number with the
Number function which is used to convert a string to a number.
const age=prompt("Please Enter Your Age");