cf.completefrontendCode editorOpen lab
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 browser dialogs honestlyTry real alert, confirm, and prompt popups and inspect their return values.
  • 02
    Read prompt values safelyExplain why prompt returns strings and when to use Number(answer).
  • 03
    Debug with the consoleChoose log, warn, error, table, and group for developer-friendly output.

Messages, questions, and developer diaries

JavaScript can talk in two very different directions. It can talk to the person using the page with small browser dialogs, and it can talk to you, the developer, through the console. This lesson keeps those two audiences separate.

Browser dialogs are the tiny popups you get from alert, confirm, and prompt. The console is the developer panel you met in Setting up your tools and used in Hello, world!. Visitors usually never see console output.

The short version

Use alert, confirm, and prompt for quick visitor-facing experiments. Use console.log, console.warn, console.error, console.table, and console.group to leave clear notes for yourself while building.

Real-life analogyDialogs are the doorbell

A doorbell interrupts the room. Everyone pauses until someone answers it. Browser dialogs feel the same: they stop the page until the visitor chooses OK, Cancel, or types an answer.

In real life: A doorbell announcement everyone must stop and hear
In JavaScript: alert(message)
In real life: A person at the door asking yes or no
In JavaScript: confirm(question)
In real life: A tiny form with one blank line
In JavaScript: prompt(question)

Where the analogy stops: A real doorbell does not return a JavaScript value. Dialogs do: undefined, true/false, a string, or null.

That interruption is why real sites usually prefer custom dialogs, including the browser’s <dialog> element, which you will meet in a later lesson. Native dialogs are still perfect for early JavaScript experiments because they are built in and easy to reason about.

alert, confirm, and prompt

INTERACTIVE

All three dialog functions live on window, the browser’s global page object. You can write alert("Hi") because the browser also makes window.alert available as a short name.

The three built-in browser dialogs
FunctionWhat the visitor seesWhat JavaScript gets back
alert(message)A message and OKundefined
confirm(question)A question with OK and Canceltrue for OK, false for Cancel
prompt(question)A question, one text box, OK, and CancelA string, "" for empty OK, or null for Cancel

Try them for real. The code is visible first, then the buttons call the browser functions. After each dialog closes, the table shows the actual returned value and its type.

Run the real browser dialogs
Dialog return valuesPop 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);
Actual returned values0 run

No dialogs have run yet. Try alert first: it blocks the page until OK.

Try it yourself

Click a button to let your browser run the real dialog function.

These buttons call the real window.alert, window.confirm, and window.prompt in your browser. Some browsers suppress repeated dialogs; if one returns immediately, the result table still shows what JavaScript received.

Notice the difference between “showing something” and “returning something.” alert shows a message, but it does not hand a useful value back to your program. confirm and prompt do hand values back, so you can store those values in variables and make decisions later.

Dialogs can be suppressed

Browsers may suppress repeated dialogs, especially if a page creates too many. That is not JavaScript changing its mind; it is the browser protecting the person using the page. If a dialog returns immediately, trust the value your code receives and keep the UI honest.

Prompt gives you a string

STEP THROUGH

The most common beginner surprise is not the popup itself. It is the value that comes back. prompt always returns text when OK is clicked, even if the text looks like a number. If the user types 25, JavaScript receives the string "25".

Step through this tiny age example. Change what the user did, then predict the two console lines. This lesson only shows the practical fix, Number(answer). The full Type conversion lesson explains why each conversion happens.

Prompt returns text: step through the gotcha
Step 0 of 4Ready
Your turn: follow the blue line

Pick what the user did in the prompt, then step through the exact values. This is a recorded replay, not a live prompt popup.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
console.log(answer + 1);const fixed = Number(answer) + 1;console.log(fixed);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Choose what the user did in the prompt

Changing the choice starts a fresh replay. Predict lines 2 and 4 before stepping.

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 has three important outcomes: typed text like "25", the empty string "" when OK is pressed with nothing typed, and null when Cancel is pressed. Check for Cancel before treating the answer like ordinary text.

console.log, warn, and error

INTERACTIVE

The console is not for the visitor. It is your developer diary and walkie-talkie: a place where code can report what it is doing while you build and debug. You already saw console.log in Hello, world!; now give each message a purpose.

Real-life analogyThe console is a dashboard

A car dashboard has ordinary information, yellow lights for things to check soon, and red lights for serious problems. Console methods use the same idea: pick the method that matches the importance of the note.

In real life: A normal note in your diary
In JavaScript: console.log(...) or console.info(...)
In real life: A yellow warning light
In JavaScript: console.warn(...)
In real life: A red warning light
In JavaScript: console.error(...)
In real life: A labeled folder of notes
In JavaScript: console.group(...) and console.groupEnd()

Where the analogy stops: Console messages help developers, but they do not fix bugs automatically and they do not show a friendly message on the web page.

Basic console methods
MethodUse it whenTypical DevTools display
console.log(value)You want a general note or a variable’s valuePlain console entry
console.info(value)You want an informational noteOften similar to log
console.warn(value)Something is unusual but the program can continueWarning styling
console.error(value)Something failed and deserves attentionError styling and sometimes a stack trace

The experiment below calls the real console methods and also renders a simplified picture inside the page. Open DevTools to see the real output beside it.

Console mirror: real calls, simplified picture
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();
Simplified DevTools picture0 entries
Preview of console.table data
(index)namemoodtreats
0Misosleepy2
1Pixelzoomy5
Try it yourself

Open DevTools, then click a button. The real console receives the message, and this page shows a simplified mirror.

The helper calls console methods directly and stores the same data for this in-page mirror. It does not replace or monkey-patch the global console.

console.table and grouping

When a value has shape, choose a console method that shows that shape. An array of objects is easier to scan with console.table than with one long console.log. Related messages are easier to scan when wrapped in console.group and console.groupEnd.

  • console.table(rows) shows an index column and one column per property, like a small spreadsheet.
  • console.group("Label") starts a collapsible folder in many DevTools consoles.
  • console.groupEnd() closes the current group.
  • console.count("label") counts how many times that label was used.
  • console.time("label") and console.timeEnd("label") time a small task while you investigate performance.
Keep console output temporary

Console calls are wonderful while learning and debugging. Before shipping a real feature, remove noisy logs or turn them into proper user-facing messages and error handling.

Which one would you use?

SORTING GAME

Choose by audience and answer shape. Is the message for the visitor or the developer? Does the visitor need to answer yes/no, type one value, or just read an announcement?

Choose the right talking tool
  • Tell a learner: “Saved!” and wait until they press OK
  • Ask “Delete this file?” and continue only for OK
  • Ask for one name before greeting the visitor
  • Tell a developer that a request failed while testing
  • Check the value stored in a variable named total
  • Ask “Leave without saving?”
  • Ask for a six-digit code typed by the user
  • Stop everything to show “You are offline” in a tiny demo
Try it yourself
0 of 8 correct

Sort each scenario. 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 tiny demos, dialogs are quick and clear. In real interfaces, you will usually replace them with HTML on the page so you can style it, keep it accessible, and avoid blocking everything.

  1. First experiments: ask for a name with prompt, then greet with alert.
  2. Careful actions: confirm a destructive step, but compare the result as a boolean: if (confirm("Delete?")).
  3. Debugging: log labels with values, like console.log("total", total), so future you understands the note.
  4. Data inspection: use console.table for arrays of objects and console.group for a sequence of related logs.

If you want a reminder of why "5" + 1 becomes "51", revisit Why JavaScript?. If you wonder how a function can remember settings for a custom dialog, that is the idea behind Closures.

Common misconceptions

“console.log shows a message to users.”

It shows a message in developer tools. Use page content, a custom dialog, or a native dialog for visitor-facing communication.

“prompt returns a number when the user types digits.”

It returns a string for OK. Convert deliberately with Number(answer) when you need arithmetic.

“Cancel and empty OK are the same.”

Cancel returns null. Empty OK returns "". Those mean different things in your program.

“confirm returns the string "true".”

It returns the boolean true or false. Comparing it to "true" is a bug.

“console.error is the same as throwing an error.”

console.error reports a message. It does not stop the program by itself. You will read real thrown errors in the next lesson, Reading error messages.

Practice: talk carefully

5 EXERCISES
Exercise 1 · Warm-upGreet the user 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 user 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 array 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 debugging 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 enters the if block, even when OK is clicked. What type does confirm return?

          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.

            Quiz: check your understanding

            7 QUESTIONS

            Answer once before reading the explanations. Several questions ask you to separate visitor-facing dialogs from developer-facing console messages.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7What does alert("Hi") return after the user presses OK?

              Choose an answer to see the explanation.

            2. Question 2 of 7Which dialog asks a yes/no-style question?

              Choose an answer to see the explanation.

            3. Question 3 of 7What does this print if the user 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 7What should you use for a developer-only warning?

              Choose an answer to see the explanation.

            5. Question 5 of 7Which console method is best for an array of similar objects?

              Choose an answer to see the explanation.

            6. Question 6 of 7What does this print when OK is clicked?

              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 7Why do real websites usually avoid browser dialogs for main UI?

              Choose an answer to see the explanation.

            Key takeaways

            • alert announces and returns undefined.
            • confirm asks OK/Cancel and returns a boolean.
            • prompt asks for one text answer: a string, "", or null.
            • The console is for developers; visitors do not see ordinary console output.
            • Use console.warn, console.error, console.table, and console.group to make debugging output easier to read.

            Remember the one-liner.
            Dialogs talk to the visitor; the console talks to the developer.

            Up next: Reading error messages. You will learn how SyntaxError, ReferenceError, TypeError, and stack traces help you find the exact line that went wrong.

            CompleteFrontend Clear concepts. Working examples.