User Input
So far, all the programs we've written generate output, such as text in the console window or blocks in the game. Sometimes the programs also need to collect user input. For example, a map program can ask you which city you are interested in. There are several different ways to collect user input. In JavaScript, prompt()
is a user-interface function, it allows us to get a piece of text from user.
The prompt()
function displays a piece of text as prompt message to the user, then it waits for the user to input some text. The input text is returned as a string by the prompt()
function.
prompt(title)
title
is a string text to show to the user.
Example
let name = prompt("Please enter your name here:");
console.log('Hello, '+ name + '!');
Type your name into the input box then click "OK". Your name will be printed in the console window.
Input a number
Sometimes we need the user to input a number. But the prompt()
function always return a string. If you attempt to use that string as a number, sometimes you get the correct result and other times you don't. JavaScript tries to be smart and convert string into number when it makes sense. But it's better not rely on that behavior and always convert into number type when a number is expected. This can be achieved with the Number()
function:
// prompt user
let n = Number(prompt('Enter a number: '));
console.log(n + ' * ' + n + ' = ' + n*n);
If you input 5
, the console will show 5 * 5 = 25
.