Please support this book: buy it or donate

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:

  • console.log()
  • console.error()

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

There are two variants of this operation:

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

7.1.1. Printing multiple values

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

  1. console.log('abc', 123, true);
  2. // Output:
  3. // 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:

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

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

  • %s converts the corresponding value to a string and inserts it.
  1. console.log('%s %s', 'abc', 123);
  2. // Output:
  3. // abc 123
  • %o inserts a string representation of an object.
  1. console.log('%o', {foo: 123, bar: 'abc'});
  2. // Output:
  3. // { foo: 123, bar: 'abc' }
  • %j converts a value to a JSON string and inserts it.
  1. console.log('%j', {foo: 123, bar: 'abc'});
  2. // Output:
  3. // {"foo":123,"bar":"abc"}
  • %% inserts a single %.
  1. console.log('%s%%', 99);
  2. // Output:
  3. // 99%

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:

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

Output:

  1. {
  2. "first": "Jane",
  3. "last": "Doe"
  4. }