Output & the Console

A program that can't show its results isn't much use. JavaScript has several ways to produce output — the console for developers, the page itself for users, and dialog boxes for quick interruptions. Knowing which to use, and how to read the console, makes learning much faster.

console.log and friends

console.log() prints any number of values, separated by spaces:

JS log.js
const name = "Ada";
const year = 1843;

console.log("Hello");
console.log(name, "wrote a program in", year);
console.log([1, 2, 3], { language: "JavaScript" });
Output
Hello
Ada wrote a program in 1843
[ 1, 2, 3 ] { language: 'JavaScript' }

The console has a few more methods that look different in browser developer tools, which helps important messages stand out:

JS levels.js
console.info("Server started");     // informational
console.warn("Disk space is low");   // yellow warning
console.error("Could not connect");  // red error, with a stack trace
console.table([{ id: 1, name: "Ann" }, { id: 2, name: "Ben" }]); // a table
console.group("Order 42");           // indents the lines that follow
console.log("2 items");
console.groupEnd();

console.table is especially useful for arrays of objects — try it in your browser's console.

Opening the developer tools

Every desktop browser has built-in developer tools:

  • Windows / Linux: F12 or Ctrl+Shift+J (Chrome, Edge)
  • Mac: Cmd+Option+J (Chrome) or Cmd+Option+C (Safari, after enabling the Develop menu)

The Console tab shows output and errors, and you can type JavaScript at its prompt to run it immediately. Errors include the file name and line number — click it to jump straight to the problem.

Writing into the page

Users never see the console. To show them something, change an element's content (lessons 42–43 go much deeper):

Try it yourself
Result

textContent sets plain text. There's also innerHTML, which interprets the string as HTML — powerful, but dangerous with any text that came from a user, because it can inject scripts. Prefer textContent unless you specifically need HTML.

Dialog boxes

Browsers have three built-in dialogs. They pause everything until the user responds, which makes them annoying in real sites, but they're convenient for quick experiments:

JS dialogs.js
alert("Saved!");                              // message with an OK button
const ok = confirm("Delete this file?");      // true for OK, false for Cancel
const name = prompt("What's your name?", ""); // text the user typed, or null

Real interfaces use custom-built dialogs instead, such as the HTML <dialog> element.

document.write — avoid it

Older tutorials use document.write() to print to the page. If it runs after the page has loaded, it erases the whole document. It's considered obsolete; use textContent or the DOM methods in lesson 43 instead.

Try it yourself

Try it yourself
Console output