Talking to the user
Show messages, ask yes/no or short-answer questions, and leave useful notes in the developer console with JavaScript dialogs and console methods.
- 01Use the three browser dialogsOpen real alert, confirm, and prompt pop-ups, and see the value each one gives back to your code.
- 02Handle prompt answers safelyExplain why prompt gives back text, and when to turn it into a number with Number(answer).
- 03Leave clear notes in the consolePick log, warn, error, table, or group for each kind of note to yourself.
Two ways JavaScript can talk
JavaScript can talk to two different people:
- The visitor: the person using the page. JavaScript talks to them with small pop-up boxes called dialogs.
- You, the developer: the person building the page. JavaScript talks to you through the console.
Keep these two apart. This lesson shows the tools for each one.
alert shows up on the page, so the visitor sees it. A console.log message shows up in the Console, which only you, the developer, usually look at.The dialogs come from three functions: alert, confirm, and prompt. The console is a panel in the browser's developer tools, called DevTools for short. You met it in Setting up your tools and used it in Hello, world!. Visitors usually never open it, so they don't see what you print there.
To talk to the visitor in a quick test, use alert, confirm, and prompt. To leave notes for yourself while you build, use console.log, console.warn, console.error, console.table, and console.group.
When the doorbell rings, you stop what you are doing. You can't carry on until you answer the door. Dialogs work the same way. The page stops until the visitor presses OK or Cancel, or types an answer.
- In real life: Someone at the door says "Your parcel is here." You say OK.
- In JavaScript:
alert(message) - In real life: Someone asks "Can I come in?" You say yes or no.
- In JavaScript:
confirm(question) - In real life: Someone asks "What is your name?" You tell them.
- In JavaScript:
prompt(question)
Because dialogs stop the whole page, real websites usually build their own pop-ups with HTML instead. One way is the <dialog> element; you'll meet it in a later lesson. The built-in dialogs are still great for your first experiments. They need no setup, and they are easy to understand.
alert, confirm, and prompt
INTERACTIVEAll three dialog functions belong to window. window is an object the browser gives your code. It stands for the browser tab your page is in. So you could write window.alert("Hi"). The browser also lets you leave out window. and write just alert("Hi").
Dialogs are part of the browser, not part of the JavaScript language itself. Node.js runs JavaScript outside a browser, in a terminal. It has no page and no window, so it has no alert. A terminal program asks for input in other ways.
The table uses a few words for kinds of values:
- A string is a piece of text in quotes, like
"Asha".""is the empty string: text with nothing in it. - A boolean is one of two values:
trueorfalse. undefinedmeans "no value here".nullalso means "no value".promptuses it to say the visitor pressed Cancel.
Read each row as: "when I call this, the visitor sees this, and my code gets this back."
| When you call | What the visitor sees | What your code gets back |
|---|---|---|
alert(message) | A message and an OK button. | undefined, which means nothing useful. |
confirm(question) | A question with OK and Cancel buttons. | true for OK. false for Cancel. |
prompt(question) | A question, one text box, and OK and Cancel buttons. | The typed text, as a string. "" for OK with an empty box. null for Cancel. |
alert gives back nothing useful. confirm gives back true or false. prompt gives back the typed text, or null after Cancel.Here is a short alert example:
const visitor = "Asha";
alert("Welcome, " + visitor + "!");
console.log("The welcome dialog closed");Line 1 keeps the visitor's name in a variable. Line 2 builds the message Welcome, Asha! and shows it in a dialog. The page stops here until the visitor presses OK. Then line 3 runs and prints The welcome dialog closed in the console. alert gives back undefined, so this code doesn't keep its result.
Now try all three for real. The code comes first. Each button below calls the real browser function. When the dialog closes, the table shows the value your code got back and its type. typeof is a JavaScript word that tells you a value's type, such as "string" or "boolean".
const alertResult = alert("Welcome, Ada!");const confirmResult = confirm("Delete the draft?");const promptResult = prompt("What is your name?"); console.log(alertResult, typeof alertResult);console.log(confirmResult, typeof confirmResult);console.log(promptResult, typeof promptResult);No dialogs have run yet. Try alert first: the page stops until you press OK.
Click a button. Your browser will open the real dialog.
A confirm answer is useful because your code can use it to choose what to do next. An if statement does the choosing: it runs its first block when the condition is true, and the else block when it is false.
The next replay uses the same true or false a browser gives back. Choose OK, and confirmed is true, so the "deleted" line runs. Choose Cancel, and confirmed is false, so the "kept" line runs.
Choose an answer, then follow true or false into the block that runs. This is a recorded replay, not a real confirm pop-up.
script
if (confirmed) { console.log("Draft deleted");} else { console.log("Draft kept");}const shouldSave = confirm("Save this draft?");
const message = shouldSave ? "Draft saved" : "Draft not saved";
console.log(message);Line 1 asks the question and keeps the answer, true or false, in shouldSave. Line 2 picks one of two messages. The ? : works like a short if:
- If
shouldSaveistrue, it picks the text after?,"Draft saved". - If
shouldSaveisfalse, it picks the text after:,"Draft not saved".
Line 3 prints the message it picked. Use this pattern before a small action that the visitor can undo.
Use the answer from confirm directly as the condition. It is already true or false. Don't write confirmed === "true". The === checks whether two values are exactly the same. Here it compares the boolean true with the text "true". They are different types, so the result is false, even when the visitor pressed OK.
Showing something is not the same as giving something back:
alertshows a message. It gives nothing useful back to your code.confirmandpromptgive back an answer. You can keep it in a variable and use it later.
If a page opens many dialogs in a row, the browser may stop showing them. This protects the visitor from a page that keeps interrupting. Then the dialog function returns straight away, without waiting for the visitor. So use the value your code actually got back. Don't assume the visitor answered.
Prompt gives you a string
STEP THROUGHThe pop-up itself rarely surprises beginners. The value it gives back often does. When the visitor presses OK, prompt always gives back text, even if the text looks like a number. If the visitor types 25, your code gets the string "25", not the number 25.
prompt gives back text, so the visitor's 25 arrives as "25". With text on one side, + joins: "251". Turn the text into a number first with Number(), and + adds: 26.Step through this short age example. Choose what the visitor did, then guess the two console lines before you step. The fix here is Number(answer), which turns the text into a number. The Type conversion lesson explains all the rules later.
Pick what the visitor did in the prompt, then step through the values. This is a recorded replay, not a real prompt pop-up.
script
console.log(answer + 1);const fixed = Number(answer) + 1;console.log(fixed);prompt can give back three kinds of answer:
- Typed text, like
"25". - The empty string
"", when the visitor presses OK with nothing typed. null, when the visitor presses Cancel.
Check for Cancel first. Only then treat the answer as text.
const name = prompt("What name should appear on your profile?");
const displayName = name === null || name.trim() === "" ? "Guest" : name.trim();
console.log("Profile name:", displayName);Line 1 gets the typed text, or null for Cancel. Line 2 picks the name to show:
name.trim()removes spaces from both ends of the text. So" Asha "becomes"Asha".||means "or". If the visitor pressed Cancel, or left the box empty or full of spaces, the name isGuest.- Otherwise, the name is the text with the spaces removed.
The null check comes first, because null is not text and has no trim(). Line 3 prints Profile name: Asha when the visitor typed Asha . It prints Profile name: Guest for Cancel or an empty answer.
const answer = prompt("How old are you?");
const age = Number(answer);
if (answer === null || answer.trim() === "" || Number.isNaN(age)) {
console.log("Enter an age using digits");
} else {
console.log("Next year:", age + 1);
}Line 1 asks for text. Line 2 tries to turn it into a number. If the text is not a number, such as tea, Number gives back NaN, which means "Not a Number". Line 4 checks for three problems before any math happens:
answer === null: the visitor pressed Cancel.answer.trim() === "": the box was empty, or held only spaces.Number.isNaN(age): the text was not a number.
If any of these is true, line 5 prints Enter an age using digits. Otherwise, line 7 adds 1. For 25, it prints Next year: 26.
console.log, warn, and error
INTERACTIVEThe console is not for the visitor. It is for you. Your code can print notes there while you build the page and fix its bugs. You already used console.log in Hello, world!. Now you'll pick a different method for each kind of note.
A car dashboard shows normal readings, yellow lights for things to check soon, and red lights for real problems. The console works the same way. Pick the method that matches how important your note is.
- In real life: A normal reading, like the speed
- In JavaScript:
console.log(...)orconsole.info(...) - In real life: A yellow light: check this soon
- In JavaScript:
console.warn(...) - In real life: A red light: something went wrong
- In JavaScript:
console.error(...)
Read each row as: "for this kind of note, I call this method, and DevTools shows it like this."
| When you call | Use it for | How DevTools shows it |
|---|---|---|
console.log(value) | A general note, or the value in a variable. | As a plain line. |
console.info(value) | A note that gives information. | Usually the same as console.log. |
console.warn(value) | Something odd that doesn't stop the program. | As a yellow warning line. |
console.error(value) | Something that failed and needs your attention. | As a red error line. It may also list the function calls that led there. That list is called a stack trace. |
The experiment below calls the real console methods. It also draws a simple copy of the output on this page. Open DevTools to see the real output next to it.
const pets = [ { name: "Miso", mood: "sleepy", treats: 2 }, { name: "Pixel", mood: "zoomy", treats: 5 },]; console.log("Checking pets", pets.length);console.warn("Miso needs water");console.error("Toy basket is empty");console.group("Pet report");console.table(pets);console.groupEnd();| (index) | name | mood | treats |
|---|---|---|---|
| 0 | Miso | sleepy | 2 |
| 1 | Pixel | zoomy | 5 |
Open DevTools, then click a button. The real console gets the message, and this page shows a simple copy.
console.table, groups, counts, and timers
Some values have a shape. For example, a list of objects that all have the same properties. Pick a console method that shows that shape:
console.table(rows)shows a list of objects as a small spreadsheet. It has one column for each property, plus an index column that numbers the rows from 0.console.group("Label")starts a folder of notes. In most DevTools, you can click it to open or close it.console.groupEnd()closes the folder you opened last.console.count("label")prints how many times you have used that label so far.console.time("label")starts a timer.console.timeEnd("label")stops it and prints how long it took. Use them to measure how long a small task takes.
const cart = ["tea", "bread"];
const total = 7;
console.log("cart items", cart.length);
console.log("cart total", total);Line 1 makes a cart: a list with two items. Line 2 keeps the total, 7. Lines 4 and 5 print a label before each value. cart.length is the number of items in the list. So DevTools prints cart items 2 and cart total 7. When several numbers are on screen, the labels tell you which is which.
Console notes are great while you learn and fix bugs. Before you put a real feature online, remove the notes you don't need. If the visitor needs to know something, show it on the page instead.
Which one would you use?
SORTING GAMETo pick the right tool, ask two questions:
- Who is the message for: the visitor, or you?
- What does the visitor need to do: just read it, answer yes or no, or type one answer?
- Tell a learner “Saved!” and wait until they press OK
- Ask “Delete this file?” and carry on only after OK
- Ask for the visitor's name before greeting them
- Tell yourself, while testing, that loading some data failed
- Check the value in a variable named
total - Ask “Leave without saving?”
- Ask the visitor to type a six-digit code
- Stop everything to show “You are offline” in a small demo
Put each case under the right tool. Read every explanation, especially when you guess wrong.
Where you will use this
In small demos, dialogs are quick and clear. In real websites, you'll usually show the message on the page with HTML instead. That way you can style it, make it work for everyone (including people who use screen readers), and avoid stopping the whole page.
const name = prompt("What is your name?");const greeting = name === null ? "Greeting canceled" : "Hello, " + name + "!";console.log(greeting);Line 1 asks for a name. It keeps either the typed text or null. Line 2 picks a message. If name is null, the visitor pressed Cancel, so the code doesn't treat it as a name. Line 3 prints the message. If the visitor types Asha, it prints Hello, Asha!. If they press Cancel, it prints Greeting canceled.
An empty box still counts as an answer here. So OK with nothing typed prints Hello, !. A real form would check for that too, and show a helpful message on the page. The first step is to know that only null means Cancel.
Where these tools show up:
- First experiments: ask for a name with
prompt, then greet the visitor withalert. - Careful actions: ask with
confirmbefore deleting something. Use the answer directly as the condition:if (confirm("Delete?")). - Fixing bugs: print a label with each value, like
console.log("total", total). Later, you'll still know what each note meant. - Looking at data: use
console.tablefor a list of objects. Useconsole.groupfor several notes that belong together.
Want a reminder of why "5" + 1 becomes "51"? Look back at Why JavaScript?. Later, the Closures lesson shows how a function can remember settings. That is useful when you build your own dialog.
Common misconceptions
“console.log shows a message to visitors.”
It shows a message in DevTools, and visitors usually don't open DevTools. To tell the visitor something, put it on the page or use a dialog.
“prompt gives back a number when the visitor types digits.”
When the visitor presses OK, it gives back a string. Turn it into a number with Number(answer) before you do math with it.
“Cancel and OK with an empty box are the same.”
Cancel gives back null. OK with an empty box gives back "". Your code can tell them apart and do different things for each.
“confirm gives back the text "true".”
It gives back the boolean true or false. If you compare it with the text "true", the result is always false. That is a bug.
“console.error is the same as throwing an error.”
console.error only prints a red message. The program keeps running. Throwing an error is different: it stops the code that is running. You'll see real thrown errors in the next lesson, Reading error messages.
Practice: talk carefully
6 EXERCISESIn your browser console, ask for a name with prompt. Then greet that name with alert.
const name = prompt("What is your name?");
alert("Hello, " + name + "!");const name = prompt("What is your name?");
alert("Hello, " + name + "!");prompt gives back the typed text, and alert shows the greeting. A finished site would also check for Cancel, so it never greets null.
Pretend answer came from prompt, and the visitor typed 5. What does this print?
const answer = "5";
console.log(answer + 1);The console prints 51. The variable holds the text "5", so answer + 1 joins "5" and "1".
Run the code in DevTools. Which console method shows the list as rows and columns?
const pets = [
{ name: "Miso", mood: "sleepy" },
{ name: "Pixel", mood: "zoomy" },
];
console.table(pets);const pets = [
{ name: "Miso", mood: "sleepy" },
{ name: "Pixel", mood: "zoomy" },
];
console.table(pets);console.table(pets) shows an index column, plus one column for name and one for mood. That is easier to read than one long line.
Which method closes the group in this code?
console.group("Order form");
console.log("name", "Ada");
console.warn("coupon is missing");
console.groupEnd();console.group("Order form");
console.log("name", "Ada");
console.warn("coupon is missing");
console.groupEnd();console.group("Order form") opens the folder. console.groupEnd() closes it, so later notes are no longer inside it.
This code never runs the if block, even when the visitor presses OK. What type of value does confirm give back?
if (confirm("Delete?") === "true") {
console.log("Deleting...");
}if (confirm("Delete?")) {
console.log("Deleting...");
}confirm gives back a boolean. The old code compared that boolean with the text "true", so the condition was never true. Use the boolean directly as the condition.
A small profile page asks for a name to show. Which exact value should the code check for before it decides not to greet the visitor?
const name = prompt("What is your name?");
if (name === null) {
console.log("Greeting canceled");
} else {
console.log("Hello, " + name + "!");
}const name = prompt("What is your name?");
if (name === null) {
console.log("Greeting canceled");
} else {
console.log("Hello, " + name + "!");
}The name === null check handles Cancel. The else block handles every string, even an empty one. So Cancel and an empty answer stay separate.
Quiz: check your understanding
8 QUESTIONSAnswer each question before you read the explanations. Several questions ask the same thing: is this for the visitor (a dialog), or for you (the console)?
Question 1 of 8What does
alert("Hi")give back after the visitor presses OK?Choose an answer to see the explanation.
Question 2 of 8Which dialog asks a yes-or-no question?
Choose an answer to see the explanation.
Question 3 of 8What does this print if the visitor typed 5?
Read the code, then predictconst answer = "5"; console.log(answer + 1);Choose an answer to see the explanation.
Question 4 of 8What should you use for a warning that only you, the developer, should see?
Choose an answer to see the explanation.
Question 5 of 8Which console method is best for a list of objects that all have the same properties?
Choose an answer to see the explanation.
Question 6 of 8
confirmgave backtrue. What does this print?Read the code, then predictconst sure = true; console.log(sure === "true");Choose an answer to see the explanation.
Question 7 of 8Why do real websites usually avoid the built-in dialogs?
Choose an answer to see the explanation.
Question 8 of 8The visitor pressed Cancel in a
prompt. What does this print?Read the code, then predictconst name = null; console.log(name === null);Choose an answer to see the explanation.
Key takeaways
alertshows a message and gives backundefined.confirmasks OK or Cancel and gives backtrueorfalse.promptasks for one typed answer. It gives back a string,""for an empty box, ornullfor Cancel.- The console is for you, the developer. Visitors don't see normal console output.
console.warn,console.error,console.table, andconsole.groupmake your notes easier to read.
Remember this one line.
Dialogs talk to the visitor. The console talks to you, the developer.
Up next: Reading error messages. You'll learn what SyntaxError, ReferenceError, and TypeError mean. You'll also learn to read a stack trace: the list that points to the exact line that went wrong.