Exerpad
🔥 1
10 XP
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!

Where you'll use this
Quizzes, chatbots, calculators, login forms — every interactive program starts with reading what the user typed.

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:

  1. Read input from the user
  2. Convert to the right type
  3. Compute something
  4. Print the result
Did you know?
The first computer "bug" was a real insect: in 1947, Grace Hopper's team found a moth stuck inside their computer and taped it into the logbook — "first actual case of bug being found."

Check yourself

Pause & predict — what will this print?
let x = prompt();  // the user types: 5
console.log(x + x);