Lesson · Chapter: Input & Type Conversion+10 XP for reading
Talking to the User
So far, our programs always do the same thing. Let's make them interactive!
Reading Input
The prompt() function waits for the user to type something:
javascript
let name = prompt();
console.log("Hello,", name);
Output
Press Run to see the output.
If the user types Alex, the output is:
Hello, Alex
Input with a Message
You can show a message to tell the user what to type:
javascript
let name = prompt("What is your name?");
console.log("Hello,", name);
Output
Press Run to see the output.
Everything is a String
prompt() always gives you a string, even if the user types a number:
javascript
let age = prompt("How old are you?");
console.log(typeof age); // string
Output
Press Run to see the output.
Converting to Numbers
Use Number() to convert a string to a number:
javascript
let ageText = prompt("How old are you?");
let age = Number(ageText);
let nextYear = age + 1;
console.log("Next year you will be", nextYear);
Output
Press Run to see the output.
Or do it in one line:
javascript
let age = Number(prompt("How old are you?"));
Output
Press Run to see the output.
Without the conversion, + would glue strings together: "10" + 1 is "101", not 11!
Converting to Strings
Use String() to convert a number to a string:
javascript
let score = 100;
let message = "Your score: " + String(score);
console.log(message);
Output
Press Run to see the output.
Common Pattern
Most programs follow this pattern:
- Read input from the user
- Convert to the right type
- Compute something
- Print the result