JavaScript Console API Walkthrough JavaScript Console API Walkthrough

Page content

In this tutorial, we’ll learn JavaScript’s Console API methods with quick examples…

console.log

console.log is the most frequently used method to log values to the console:-

const name = 'Console!';

console.log('hello,', name);    //hello, Console!

We can also use String Template Literal:-

console.log(`hello, ${name}`);  //hello, Console!

We can also log multiple values in a single statement to the console:-

const key = 'value';
const number = 1;
const fruits = ['apple', 'banana', 'mango'];
const obj = {a: 1, b: 2};
console.log('key:', name, 'number:', number, 'fruits:', fruits, 'obj:', obj);
key: Console! number: 1 fruits: (3) ["apple", "banana", "mango"] obj: {a: 1, b: 2}

Just like console.log, we have other methods to log values to the console:

  • console.debug just like console.log with “debug” log level. Normally browser default log level is info and this won’t be displayed until you change log level to debug.
  • console.info just like console.log with “info” log level
  • console.warn prints a warning to the console
  • console.error prints object to the console as an error, and include a stack trace
console.debug('Let me find you');  //won't be displayed
console.info('Just FYI');
console.warn('I told you !');
console.error('I cannot do it.');
  Just FYI
➤ ⚠️ I told you !ⓧ I cannot do it.

console.assert

You can do some assertion tests using console.assert`.

The first argument is an expression that if evaluate to false, then assertion fails and the second argument gets printed to the console as an error.

// this will pass, nothing will be logged
console.assert(2 == '2', '2 not == to "2"');

// this fails, '3 not === to "3"' will be logged
console.assert(3 === '3', '3 not === to "3"');
ⓧ Assertion failed: 3 not === to "3"

You can also pass an object in the second argument which is printed when the assertion fails:

const x = 5;
const y = 3;
const reason = 'x is expected to be less than y';
console.assert(x < y, {x, y, reason});
ⓧ Assertion failed:  ➤ {x: 5, y: 3, reason: "x is expected to be less than y"}

console.clear

You can just clear the console using console.clear:

console.clear();

console.count

The console.count method is used to count the number of times it has been invoked with the same provided label. For example, here we have two counters, one for even values and one for odd values:

[1, 2, 3, 4, 5].forEach(nb => {
  if (nb % 2 === 0) {
    console.count('even');
  } else {
    console.count('odd');
  }
});
odd: 1
even: 1
odd: 2
even: 2
odd: 3

The console.countReset method is used to reset the counter to 1, if we execute below after the above example,

console.countReset('even');
console.countReset('odd');
console.count('even');
console.count('odd');
even: 1
odd: 1

console.dir

You can print all the internal properties of an object in a formatted way using console.dir

We can print prototype methods of an Array or Object using console.dir,

console.dir(["foo", "bar", "qux"]);  //Array

console.dir({a: "foo", b: "bar"});   //Object
▼ Array(3)
  0: "foo"
  1: "bar"
  2: "qux"
  length: 3
  ▼ __proto__: Array(0)
    ➤ concat: ƒ concat()
    ➤ constructor: ƒ Array()
    ➤ ...

▼ Object
  a: "foo"
  b: "bar"
➤ __proto__: Object

We can also print scopes and closures of a function using console.dir,

var outerFunc  = function(c){ 
  var a = 1;
  var innerFunc = function(d) {
    var b = 2;
    return a + b + c + d;
  }
  return innerFunc;
}
console.dir(outerFunc(3)); 
▼ ƒ innerFunc(d)
    arguments: null
    caller: null
    length: 1
    name: "innerFunc"
  ➤ prototype: {constructor: ƒ}
  ➤ __proto__: ƒ ()
  ▼ [[[Scopes]]: Scopes[2]
    ➤ 0: Closure (outerFunc) {c: 3, a: 1}
    ➤ 1: Global {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}

console.dirxml

You can print DOM element in HTML like tree structure using console.dirxml

console.dirxml(document.body);
▼ <body>
    <h1>hello</h1>
    <script>
      console.dirxml(document.body);
    </script>
  </body>

console.group

You can group the log messages together using console.group and console.groupEnd.

console.group("API Details");
console.log("Scheme : HTTPS");
console.log("Host   : example.com");
console.groupEnd();
API Details
  Scheme : HTTPS
  Host   : example.com

Please note that group messages logged using console.group are initially expanded. If you’d rather have them collapsed by default, you can use console.groupCollapsed instead:

console.groupCollapsed("API Details");
console.log("Scheme : HTTPS");
console.log("Host   : example.com");
console.groupEnd();
API Details

You can further group the messages into nested levels. That allows you to print hierarchical data to the console in a cleanly formatted manner:

console.group("API Details");
console.log("Scheme : HTTPS");
console.log("Host   : example.com");

  // nesting
  console.group("User API");
  console.log("Method   : GET");
  console.log("Endpoint : /user");

    // further nesting
    console.group("Query Parameters");
    console.log("id : 1");
    console.groupEnd();

  console.groupEnd();
console.groupEnd();
API Details
  Scheme : HTTPS
  Host   : example.com
  ▼ User API
    Method   : GET
    Endpoint : /user
    ▼ Query Parameters
      id : 1

console.table

You can print data in tabular format using console.table. This method is quite useful to visualize large objects and arrays.

var john  = { firstName: "John",  lastName: "Smith", age: 41 };
var jane  = { firstName: "Jane",  lastName: "Doe",   age: 38 };
var emily = { firstName: "Emily", lastName: "Jones", age: 12 };

console.table([john, jane, emily]);
┌─────────┬───────────┬──────────┬─────┐
│ (index) │ firstName │ lastName │ age │
├─────────┼───────────┼──────────┼─────┤
│    0    │  'John'   │ 'Smith'  │ 41  │
│    1    │  'Jane'   │  'Doe'   │ 38  │
│    2    │  'Emily'  │ 'Jones'  │ 12  │
└─────────┴───────────┴──────────┴─────┘
▶ Array(3)

You can also choose to print a few properties when working with large objects in this way:

console.table([john, jane, emily], ["firstName"]);
┌─────────┬───────────┐
│ (index) │ firstName │
├─────────┼───────────┤
│    0    │  'John'   │
│    1    │  'Jane'   │
│    2    │  'Emily'  │
└─────────┴───────────┘
▶ Array(3)

Also learn more about console.table() usage in JavaScript

console.time

You can print the time taken by a code execution by starting a timer with console.time and ending it with console.timeEnd.

The timer can have an optional label, if you use a timer with label then both console.time and console.timeEnd should have same label.

console.time('fetching data');
fetch('https://jsonplaceholder.typicode.com/users')
  .then(d => d.json())
  .then(console.log);
console.timeEnd('fetching data');
fetching data: 0.435791015625ms
▶ (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

console.trace

You can use console.trace() to print a stack trace of method execution flow to the console.

1  const first = () => { second(); };
2  const second = () => { third(); };
3  const third = () => { fourth(); };
4  const fourth = () => { console.trace("The trace"); };
5  first();

You get @ file_name:line_number in console output which you can click on to navigate to the source.

Output
▼ The trace fourth @ test:4 third @ test:3 second @ test:2 first @ test:1 (anonymous) @ test:5

console.log formatting

console.log also provide formatting to make our log messages stand out from other messages. This gives us the ability to find our important messages in the console.

  • %s format a value as a string
  • %d or %i format a value as an integer
  • %f format a value as a floating point number
  • %o is used to print as expandable DOM Element
  • %O is used to print as JavaScript object
  • %c is used to apply CSS style rules to the output string as specified by the second parameter

Let’s format the values as string, integer and floating point number:

console.log('The %s is turning %d in next %f months', 'kid', 18, 2.5);
//The kid is turning 18 in next 2.5 months

Let’s see what the fuss about printing DOM as expandable HTML element tree or JSON object tree:

console.log('%o', document.body);   //Print HTML element tree

console.log('%O', document.body);   //Print JSON object tree
▶ <body class="body" data-gr-c-s-loaded="true"> ... <body>

▶ body.body

You can print colorful formatted log messages like this:

const red = 'color:red';
const orange = 'color:orange';
const green = 'color:green';
const blue = 'color:blue';

console.log('%cHello %cWorld %cfoo %cbar', red, orange, green, blue);
Hello World foo bar

You can also print stylish banners to the console using multiple style properties:

console.log(
'%cThanks for reading %cCodingNConcepts :)',
'color: #000; font-weight: bold; font-size: 1.5rem; border: 1px solid black; padding: 5px; margin-right: 5px;',
'color: #e22d30; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);',
);
Thanks for reading   CodingNConcepts :)