completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

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.

By the end, you can
  • 01
    Use the three browser dialogsOpen real alert, confirm, and prompt pop-ups, and see the value each one gives back to your code.
  • 02
    Handle prompt answers safelyExplain why prompt gives back text, and when to turn it into a number with Number(answer).
  • 03
    Leave 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.

Your code talks in two directions. alert of Hi shows up on the page, for the visitor. console.log shows up in the Console, for you, the developer.your codepagealert("Hi")for the visitorConsoleconsole.log(...)for you, the developer
The same code can talk to two different people. A dialog such as 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.

The short version

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.

Real-life analogyA dialog is like someone at your door

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

INTERACTIVE

All 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: true or false.
  • undefined means "no value here".
  • null also means "no value". prompt uses 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."

The three built-in browser dialogs, and what each one gives back
When you callWhat the visitor seesWhat 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.
What each dialog gives back. alert gives undefined, which means nothing useful. confirm gives true or false. prompt gives the typed text, or null after Cancel.alert("Hi")undefinednothing usefulconfirm("Sure?")true / falseOK or Cancelprompt("Age?")"25" or nulltext, or Cancel
After the visitor closes a dialog, your code gets one value back. 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:

Show one welcome messagePop out in the code editor (opens in a new tab)JavaScript
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".

Run the real browser dialogs
What each dialog gives backPop out in the code editor (opens in a new tab)JavaScript
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);
Values your code got back0 run

No dialogs have run yet. Try alert first: the page stops until you press OK.

Try it yourself

Click a button. Your browser will open the real dialog.

These buttons call the real window.alert, window.confirm, and window.prompt in your browser. If a page opens many dialogs, the browser may stop showing them. Then the function returns straight away, and the table still shows the value your code got back.

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.

confirm gives back true or false: follow the choice
Step 0 of 3Ready
Your turn: follow the blue line

Choose an answer, then follow true or false into the block that runs. This is a recorded replay, not a real confirm pop-up.

Running in
  1. script
Next: line 1
if (confirmed) {  console.log("Draft deleted");} else {  console.log("Draft kept");}
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the visitor's answer

Changing the answer starts the replay again. Watch which block runs after line 2.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Save a draft only when the visitor agreesPop out in the code editor (opens in a new tab)JavaScript
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 shouldSave is true, it picks the text after ?, "Draft saved".
  • If shouldSave is false, 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:

  • alert shows a message. It gives nothing useful back to your code.
  • confirm and prompt give back an answer. You can keep it in a variable and use it later.
Browsers can block repeated dialogs

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 THROUGH

The 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.

Left: the text 25 plus 1 joins the two into the text 251. Right: Number of 25 plus 1 turns the text into a number first, so it adds and gives 26."25" + 1"251"joins textNumber("25") + 126adds numbers
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.

prompt gives back text: step through it
Step 0 of 4Ready
Your turn: follow the blue line

Pick what the visitor did in the prompt, then step through the values. This is a recorded replay, not a real prompt pop-up.

Running in
  1. script
Next: line 1
console.log(answer + 1);const fixed = Number(answer) + 1;console.log(fixed);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Choose what the visitor did in the prompt

Changing your choice starts the replay again. Guess what lines 2 and 4 print before you step.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Cancel is not an empty string

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.

Use a clean profile name or GuestPop out in the code editor (opens in a new tab)JavaScript
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 is Guest.
  • 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.

Check an age before doing mathPop out in the code editor (opens in a new tab)JavaScript
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

INTERACTIVE

The 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.

Real-life analogyThe console is like a car dashboard

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(...) or console.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."

Four basic console methods, and when to use each
When you callUse it forHow 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.

Real console calls, with a simple copy on the page
Console methodsPop out in the code editor (opens in a new tab)JavaScript
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();
Simple copy of DevTools0 entries
Preview of the console.table data
(index)namemoodtreats
0Misosleepy2
1Pixelzoomy5
Try it yourself

Open DevTools, then click a button. The real console gets the message, and this page shows a simple copy.

Each button calls the real console methods, and also keeps a copy of what they printed for the panel on this page. It doesn't change how the console itself works.

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.
Print each value with a labelPop out in the code editor (opens in a new tab)JavaScript
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.

Left: console.log of 7 prints only 7 in the Console, so you can't tell what 7 is. Right: console.log of cart total and 7 prints cart total 7, so you know what it is.console.log(7)Console77 of what?console.log("cart total", 7)Consolecart total 7says what 7 is
A number on its own leaves you guessing. Put a short label in front of the value, and the Console line says what the number is.
Remove console notes before you finish

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 GAME

To 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?
Choose the right talking tool
  • 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
Try it yourself
0 of 8 correct

Put each case under the right tool. Read every explanation, especially when you guess wrong.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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.

Greet the visitor, or say they canceledPop out in the code editor (opens in a new tab)JavaScript
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:

  1. First experiments: ask for a name with prompt, then greet the visitor with alert.
  2. Careful actions: ask with confirm before deleting something. Use the answer directly as the condition: if (confirm("Delete?")).
  3. Fixing bugs: print a label with each value, like console.log("total", total). Later, you'll still know what each note meant.
  4. Looking at data: use console.table for a list of objects. Use console.group for 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 EXERCISES
Exercise 1 · Warm-upGreet the visitor by name

In your browser console, ask for a name with prompt. Then greet that name with alert.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const name = prompt("What is your name?");
alert("Hello, " + name + "!");
    Exercise 2 · PracticePredict the prompt string

    Pretend answer came from prompt, and the visitor typed 5. What does this print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const answer = "5";
    console.log(answer + 1);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeLog rows as a table

      Run the code in DevTools. Which console method shows the list as rows and columns?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const pets = [
        { name: "Miso", mood: "sleepy" },
        { name: "Pixel", mood: "zoomy" },
      ];
      console.table(pets);

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeGroup related logs

        Which method closes the group in this code?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        console.group("Order form");
        console.log("name", "Ada");
        console.warn("coupon is missing");
        console.groupEnd();

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFind the confirm bug

          This code never runs the if block, even when the visitor presses OK. What type of value does confirm give back?

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          if (confirm("Delete?") === "true") {
            console.log("Deleting...");
          }

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeDon't greet a canceled answer

            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?

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            const name = prompt("What is your name?");
            if (name === null) {
              console.log("Greeting canceled");
            } else {
              console.log("Hello, " + name + "!");
            }

            Answer, then press Check. Spacing and letter case don’t matter.

              Quiz: check your understanding

              8 QUESTIONS

              Answer 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)?

              Lesson quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does alert("Hi") give back after the visitor presses OK?

                Choose an answer to see the explanation.

              2. Question 2 of 8Which dialog asks a yes-or-no question?

                Choose an answer to see the explanation.

              3. Question 3 of 8What does this print if the visitor typed 5?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const answer = "5";
                console.log(answer + 1);

                Choose an answer to see the explanation.

              4. Question 4 of 8What should you use for a warning that only you, the developer, should see?

                Choose an answer to see the explanation.

              5. 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.

              6. Question 6 of 8confirm gave back true. What does this print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const sure = true;
                console.log(sure === "true");

                Choose an answer to see the explanation.

              7. Question 7 of 8Why do real websites usually avoid the built-in dialogs?

                Choose an answer to see the explanation.

              8. Question 8 of 8The visitor pressed Cancel in a prompt. What does this print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const name = null;
                console.log(name === null);

                Choose an answer to see the explanation.

              Key takeaways

              • alert shows a message and gives back undefined.
              • confirm asks OK or Cancel and gives back true or false.
              • prompt asks for one typed answer. It gives back a string, "" for an empty box, or null for Cancel.
              • The console is for you, the developer. Visitors don't see normal console output.
              • console.warn, console.error, console.table, and console.group make 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.

              CompleteFrontend Clear concepts. Working examples.