JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

7. Printing information on the console (console.*)

Printing is functionality that is not part of the JavaScript language standard. However, all operations that we examine here, are supported by both browsers and Node.js.

Printing means “displaying something on the console”, where “console” is either the browser console or the terminal in which you run Node.js.

The full console.* API is documented on MDN web docs and on the Node.js website. We’ll just take a quick look at the following two operations:

7.1. Printing values: console.log() (stdout)

There are two variants of this operation:

console.log(...values: any[]): void
console.log(pattern: string, ...values: any[]): void

7.1.1. Printing multiple values

The first variant prints (text representations of) values on the console:

console.log('abc', 123, true);
// Output:
// abc 123 true

At the end, console.log() always prints a newline. Therefore, if you call it with zero arguments, it just prints a newline.

7.1.2. Printing a string with substitutions

The second variant performs string substitution:

console.log('Test: %s %j', 123, 'abc');
// Output:
// Test: 123 "abc"

These are some of the directives you can use for substitutions:

7.2. Printing error information: console.error() (stderr)

console.error() works the same as console.log(), but what it logs is considered error information. For Node.js, that means that the output goes to stderr instead of stdout on Unix.

7.3. Printing nested objects via JSON.stringify()

JSON.stringify() is occasionally useful for printing nested objects:

console.log(JSON.stringify({first: 'Jane', last: 'Doe'}, null, 2));


  "first": "Jane",
  "last": "Doe"