JavaScriptBeginner

JavaScript Input and Output: alert, prompt, confirm and console

Learn how JavaScript talks to users with alert, prompt and confirm, and how to debug with console.log, console.table, console.error and other console methods.

All JavaScript lessons

What you will learn

Every program needs to talk with people. It asks something (input) and it shows something back (output). A calculator takes your numbers and shows the answer. A login form takes your username and password and shows “Welcome”.

JavaScript in the browser has several simple tools for this. In this lesson you will learn the three dialog boxes (alert, prompt, confirm), how to use the console with more than just console.log, how to show results on the page, and when not to use the old dialog boxes in real projects.

The big picture

Tool Direction Who sees it Best for
console.log() and friends Output The developer Testing and debugging
alert() Output The user Quick messages while learning
prompt() Input The user Quick questions while learning
confirm() Input The user “Are you sure?” questions
element.textContent = ... Output The user Real websites
Form fields (<input>) Input The user Real websites

The first four are great for learning and small tools. Real websites mostly use the last two rows, and you will see them at the end of this lesson.

Note: The MyCodeNest code editor shows a Console panel for console.log, console.info, console.warn and console.error. For the other console methods in this lesson (table, group, time, and so on), press F12 in your browser and open the Console tab of DevTools.

alert: show a message

alert() shows a small pop-up box with a message and an OK button.

alert("Welcome to MyCodeNest!");

Things to know:

  • It pauses your whole page and script until the user clicks OK.
  • It always shows text. Numbers and other values are turned into text.
  • It returns undefined. There is nothing to store.
  • You cannot style it. Each browser draws its own box.
alert(42);                 // shows 42
alert("Total: " + 150);    // shows Total: 150
alert(`Hello, ${"Riya"}`); // shows Hello, Riya

You can write a message on more than one line with \n:

alert("Line one\nLine two\nLine three");

When to use alert

  • While you are learning, to see that your code ran.
  • For tiny tools you build for yourself.

When not to use it

  • On real websites. It blocks everything, looks old and is easy to ignore. Browsers may even let users switch off pop-ups from a page that shows too many.
  • For debugging. console.log is faster, and it does not interrupt you.

prompt: ask the user to type something

prompt() shows a box with a message, a text field, and OK and Cancel buttons.

const name = prompt("What is your name?");
console.log("Hello, " + name);

Its syntax is:

prompt(message, defaultValue)
  • message: the question.
  • defaultValue (optional): text that is already in the field.
const city = prompt("Which city do you live in?", "Delhi");
console.log(city);

What prompt returns

This is the part that confuses most beginners. The answer is always one of these:

User action Result
Types text and clicks OK The text as a string (even if it looks like a number)
Clicks OK with an empty field An empty string ""
Clicks Cancel or presses Esc null

So you must handle three cases, not one:

const name = prompt("What is your name?");

if (name === null) {
  console.log("You pressed Cancel");
} else if (name.trim() === "") {
  console.log("You typed nothing");
} else {
  console.log("Hello, " + name.trim() + "!");
}

trim() removes spaces from both ends, so " " counts as empty. You learned it in JavaScript Strings.

The answer is always a string

const age = prompt("How old are you?", "20");

console.log(typeof age);   // "string"
console.log(age + 1);      // "201", not 21!

Convert it with Number() before doing maths. See Type Conversion.

const age = Number(prompt("How old are you?", "20"));

console.log(typeof age);   // "number"
console.log(age + 1);      // 21

The Cancel trap

There is one nasty surprise. Number(null) is 0, not NaN. So a user who presses Cancel looks like they typed 0:

console.log(Number(null));   // 0
console.log(Number(""));     // 0
console.log(Number("abc"));  // NaN

Always check for null and an empty answer before converting:

const answer = prompt("Enter your age", "20");

if (answer === null || answer.trim() === "") {
  console.log("No age given");
} else {
  const age = Number(answer);

  if (Number.isNaN(age)) {
    console.log("That is not a number");
  } else {
    console.log("Next year you will be " + (age + 1));
  }
}

A reusable helper: ask until the answer is valid

This function keeps asking until the user types a real number, or presses Cancel:

function askNumber(message) {
  while (true) {
    const answer = prompt(message);

    if (answer === null) return null;            // user cancelled

    const number = Number(answer);
    if (answer.trim() !== "" && !Number.isNaN(number)) {
      return number;
    }

    alert("Please type a valid number.");
  }
}

const age = askNumber("How old are you?");
console.log(age === null ? "Cancelled" : "Age is " + age);

confirm: ask a yes/no question

confirm() shows a message with OK and Cancel. It returns a boolean:

  • OK → true
  • Cancel → false
const sure = confirm("Do you want to continue?");

console.log(sure);   // true or false

It fits perfectly with if:

if (confirm("Delete this file?")) {
  console.log("File deleted");
} else {
  console.log("Cancelled");
}

Real use case: protect a dangerous action

Ask before something that cannot be undone, like deleting data or leaving a page with unsaved work:

const deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete my account";
document.body.append(deleteBtn);

deleteBtn.addEventListener("click", function () {
  const sure = confirm("Delete your account? This cannot be undone.");

  if (sure) {
    console.log("Account deleted");
  } else {
    console.log("Nothing was deleted");
  }
});

On a link, combine it with event.preventDefault() to stop navigation when the user says no. You met this in preventDefault.

Dialogs block everything

alert, prompt and confirm are synchronous and blocking. While a box is open, your page is frozen: no animations run, no clicks work, no timers fire. Your code stops on that line and continues only after the user answers.

console.log("1. before");
alert("Click OK to continue");
console.log("2. after");   // runs only after you click OK

This is why they are rarely used in finished websites. They interrupt the user, cannot be styled, and some browsers hide them if a page shows too many. For real products, build your own popup with HTML and CSS, or use the built-in <dialog> element. Learn more in HTML details and dialog.

The console: your window into the code

The console is for you, the developer. Your visitors never see it, so you can print as much as you like while building. console.log is the one everyone knows, but there are many more.

The four message levels

console.log("Normal message");
console.info("Information");
console.warn("Something looks wrong");
console.error("Something failed");
Method Looks like in DevTools Use for
console.log() Plain text General output
console.info() Plain text (some browsers add an icon) Helpful facts
console.warn() Yellow background Things that could cause trouble
console.error() Red background Failures

Using the right level makes real problems easy to spot. You can also filter by level in DevTools.

console.log accepts any number of arguments, separated by commas:

const name = "Riya";
const age = 20;

console.log("Name:", name, "Age:", age);
console.log("Is adult?", age >= 18);
console.log("Scores:", [90, 85, 70]);

Printing a label together with the value saves you from guessing which line is which.

Tip: Wrap variables in curly braces to get free labels: console.log({ name, age }) prints { name: "Riya", age: 20 }.

console.table: arrays and objects as a table

When you have a list of objects, a table is much easier to read than nested brackets.

const users = [
  { name: "Riya", age: 20, city: "Delhi" },
  { name: "Karan", age: 17, city: "Mumbai" },
  { name: "Neha", age: 25, city: "Pune" }
];

console.table(users);

DevTools draws a table with the columns (index), name, age and city, one row per user. You can show only some columns by passing a second argument:

const users = [
  { name: "Riya", age: 20, city: "Delhi" },
  { name: "Karan", age: 17, city: "Mumbai" }
];

console.table(users, ["name", "city"]);

It also works for a single object (one row per property) and for simple arrays (one row per item).

console.group("User details");
console.log("Name: Riya");
console.log("Age: 20");
console.groupEnd();

console.log("Back to normal");

Everything between group and groupEnd is indented and can be collapsed. Use console.groupCollapsed() to start collapsed. Groups can be nested.

console.time: measure how long code takes

console.time("loop");

let total = 0;
for (let i = 0; i < 1000000; i++) {
  total += i;
}

console.timeEnd("loop");   // prints something like "loop: 3.2 ms"

The label in time and timeEnd must be the same text, so the browser knows which timer to stop.

console.count: count how often something happens

function visit() {
  console.count("visits");
}

visit();   // visits: 1
visit();   // visits: 2
visit();   // visits: 3

console.countReset("visits");
visit();   // visits: 1

Great for answering “how many times did this function run?”.

console.assert: print only when something is wrong

console.assert(condition, message) prints an error only if the condition is false. If it is true, nothing happens.

const age = 15;

console.assert(age >= 18, "User must be an adult, got", age);
// Assertion failed: User must be an adult, got 15

console.dir, console.trace and console.clear

const button = document.createElement("button");

console.log(button);   // shows the HTML: <button></button>
console.dir(button);   // shows the object with all its properties
function inner() {
  console.trace("Who called me?");
}

function outer() {
  inner();
}

outer();   // prints the path: inner <- outer <- (anonymous)

console.clear() wipes the console. console.debug() works like log, but many browsers hide these messages unless you enable the Verbose level.

Style and format your messages

In DevTools you can use format codes inside the first string:

Code Inserts
%s A string
%d or %i A number (integer)
%f A number (decimal)
%o or %O An object
%c Applies CSS to the text that follows
console.log("Hello %s, you are %d years old", "Riya", 20);

console.log("%cBig red text", "color: red; font-size: 24px; font-weight: bold;");

Modern template literals are often easier than %s: console.log(Hello ${name}). See JavaScript Strings.

Quick reference

I want to… Use
Print a value console.log(value)
Print a warning or error console.warn() / console.error()
See a list of objects clearly console.table(list)
Group related lines console.group() / console.groupEnd()
Time a piece of code console.time() / console.timeEnd()
Count calls console.count()
Check an assumption console.assert(condition, message)
See the call path console.trace()

For breakpoints, the call stack and the other DevTools panels, read Debugging and DevTools.

Output on the real page

For visitors, you put results on the page, usually with textContent:

<p id="output">Your messages appear here.</p>
const output = document.getElementById("output");

output.textContent = "Hello from JavaScript!";

textContent treats everything as plain text. That is the safe choice for anything that came from a user. If you use innerHTML, a user could type HTML or a script tag and your page would run it. This is a classic security hole called XSS, so use innerHTML only for HTML that you wrote yourself.

const output = document.getElementById("output");
const userText = "<img src=x onerror=alert('hacked')>";

output.textContent = userText;   // safe: shows the text exactly as typed
// output.innerHTML = userText;  // dangerous: runs the user's code

What about document.write?

You may see document.write("Hello") in old tutorials. Avoid it. If it runs after the page has loaded, it erases the entire page. Use textContent or DOM methods instead.

Putting it all together

Mini project: number guessing game

The computer picks a secret number from 1 to 10. The player has 3 tries. It uses prompt for input, alert for output and console to help us while testing.

const secret = Math.floor(Math.random() * 10) + 1;
console.log("Secret (for testing only):", secret);

let won = false;

for (let attempt = 1; attempt <= 3; attempt++) {
  const answer = prompt("Guess a number from 1 to 10 (try " + attempt + " of 3)");

  if (answer === null) {
    alert("Game cancelled.");
    break;
  }

  const guess = Number(answer);

  if (answer.trim() === "" || Number.isNaN(guess)) {
    alert("Please type a number.");
  } else if (guess === secret) {
    alert("Correct! You win!");
    won = true;
    break;
  } else if (guess < secret) {
    alert("Too low.");
  } else {
    alert("Too high.");
  }
}

if (!won) {
  console.log("Game over. The number was", secret);
}

This uses loops (JavaScript Loops), conditions (JavaScript Conditions) and the Math object.

Mini project: tip calculator on the page

Ask for the bill, check it carefully, then show the result on the page instead of in an alert:

<button id="tip-btn">Tip calculator</button>
<p id="output">Your messages appear here.</p>
const output = document.getElementById("output");

document.getElementById("tip-btn").addEventListener("click", function () {
  const answer = prompt("Bill amount?", "1000");
  if (answer === null) return;   // cancelled

  const bill = Number(answer);

  if (answer.trim() === "" || Number.isNaN(bill) || bill <= 0) {
    alert("Please type a valid amount.");
    return;
  }

  const tip = bill * 0.1;
  const total = bill + tip;

  output.textContent = `Bill ${bill} + 10% tip ${tip} = ${total}`;
  console.log({ bill, tip, total });
});

Notice that the dialogs run only when the button is clicked. If you call prompt at the top of your script, it appears the moment the page loads, which is annoying.

Common mistakes

  • Treating the prompt answer as a number. It is always a string. "5" + 1 is "51". Use Number().
  • Forgetting that Cancel returns null. And Number(null) is 0. Check for null first.
  • Not checking for an empty answer. Number("") is 0 too.
  • Comparing confirm() to strings. It returns true or false, not "OK".
  • Calling prompt or alert on page load without a good reason. It blocks the page before the user sees anything.
  • Using alert to debug. It stops your code and is awkward for objects. Use console.log, or console.table for lists.
  • Printing an object in alert. You get [object Object]. Use JSON.stringify(obj) or the console.
  • Expecting console.table or console.group to show in the editor’s Console panel. Open real DevTools with F12.
  • Mismatching labels in console.time and console.timeEnd. If the text is different, no time is printed.
  • Leaving console.log calls in finished code. They clutter the console and may expose private data. Remove them before you publish.
  • Using innerHTML to show user text. Use textContent.
  • Using document.write. It can wipe the page.

Practice

  1. Click Practice in Editor and press Say hello. Type your name, then try Cancel, then try an empty answer. Check that all three cases show a different message.
  2. Write a script that asks for the user’s birth year with prompt and shows the age with alert.
  3. Ask for two numbers with the askNumber helper from this lesson and print their sum, difference, product and quotient with console.log.
  4. Build a “Clear all items?” button that asks confirm first, and only then empties a list.
  5. Print an array of 3 products (name, price, stock) with console.table. Then print only the name and price columns.
  6. Use console.group to print the details of two different users, one group each.
  7. Use console.time and console.timeEnd to measure a loop that adds the numbers from 1 to 5,000,000.
  8. Write a function that calls console.count("clicks") and wire it to a button. Press the button 5 times.
  9. Use console.assert to check that cart.length > 0 before checkout. Test it with an empty array.
  10. Rewrite the guessing game so it shows messages on the page with textContent instead of alert. Which version do you like better as a user?
  11. Challenge: build a “Rock, Paper, Scissors” game. Ask the player with prompt, let the computer pick randomly, and show the result on the page and in the console.
  12. Challenge: write a function ask(question, validator) that keeps asking with prompt until validator(answer) returns true or the user cancels.

Recap

  • Input is information going into your program. Output is information coming out.
  • alert(message) shows a message. prompt(message, default) asks for text and returns a string, "" or null. confirm(message) returns true or false.
  • Always handle null (Cancel) and empty answers, and convert with Number() before maths.
  • Dialogs block the page and cannot be styled. They are good for learning and quick tools, not for polished websites.
  • The console is for developers: log, info, warn, error, plus table, group, time, count, assert, dir and trace.
  • Use textContent to show results on the page. Avoid innerHTML for user text and avoid document.write.
  • Real websites collect input with form fields and show output on the page. You will learn forms in the lessons ahead.
  • Next you will explore the browser objects (window, location, history, navigator and screen) that let your code talk to the browser itself.