User Tools

Site Tools


js:console

JavaScript : Tools : Console

A very handy tool for JavaScript development is the console object. You surely know console.log but that is just the tip of the iceberg. The following is nothing but a small overview.

For more information head to MDN

The following commands output logging information at different log levels (the first command clears the console)

Logging

console.clear()
console.debug("debug information")
console.error("error")
console.info("some information")
console.log("your typical log output")
console.warn("warning")

This is how these outputs present in

Grouping

Here is an illustration of how grouping of console messages works

console.group("Earth")
console.debug("We reached Earth")
console.group("North America")
console.debug("We reached North America")
console.group("Canada")
console.debug("We reached Canada")
console.groupCollapsed("Québec")
console.debug("Finalement nous sommes arrivés à Québec.")
console.debug("We have finally arrived at Québec.")
console.groupEnd("Québec")
console.groupEnd("Canada")
console.groupEnd("North America")
console.group("Europe")
console.debug("Hemos llegado en Europa")
console.group("España")
console.debug("Hemos llegado en España")
console.group("Gibraltar")
console.debug("We have finally arrived at Gibraltar.")
console.groupEnd("Gibraltar")
console.groupEnd("España")
console.groupEnd("Europe")
console.groupEnd("Earth")

Note the use of groupCollapsed instead of group for Québec. Here is the output (note that the Québec section is collapsed).

Timing

Here is an example console's time measurement capabilities:

console.clear()
console.time('variant a')
for (var i = 0; i < 1000000000; i++) {
  if (i%200000000 === 0) console.timeLog('variant a')
}
console.timeEnd('variant a')
 
console.time('variant b')
var i = 0;
while (i++ < 1000000000) {
  if (i%200000000 === 0) console.timeLog('variant b')
}
console.timeEnd('variant b')

Here's the output (to be honest I did not expect that large a difference):

Stack trace

The stack trace is the “how did I end up here” information. Here is an example how it can be used:

function f(a) {
  console.trace()
  return a
}
function g(b) {
  return f(b)
}
function h(c) {
  return g(c)
}
h("lorem ipsum")

And here is what you get using Opera's developer tools:

Assertions

Assertions using console.assert() are similar to console.error() but only display if a certain (error) condition is not met. Example:

function listElement (i) {
    const list = ['lorem', 'ipsum', 'dolor', 'sit', 'amet']
    console.assert(typeof list[i] !== 'undefined', 'no list element number %i', i)
    return list[i]
}
console.log(listElement(1), listElement(3), listElement(5), listElement(-1))

Here's the result in Opera's developer tools:

All That Counts

You can use console.count() and console.countReset() to count how frequently a certain section of code is executed (i.e. to check how frequently a certain event is triggered):

console.countReset('click/touch')
window.addEventListener('click', () => console.count('click/touch'))
window.addEventListener('touch', () => console.count('click/touch'))

And here's what happens:

Wonder what the error 429 is about? Well, that server simply does not like if you bother it, for Geek calends see Merriam-Webster:

Table output

console.table() created nice table outputs Here is a simple example outputting an array:

console.clear()
var counting = [
  "one Mississippi",
  "two Mississippi",
  "three Mississippi"
]
console.table(counting)

And here is the actual output:

You can also use table() it for an object:

console.clear()
var counting = {
  one: "one Mississippi",
  two: "two Mississippi",
  three: "three Mississippi"
}
console.table(counting)

This results in the following output:

But it does not stop here. Let's us see what happens if the object has an additional level (here it is different language versions):

console.clear()
var counting = {
  one: {
    de: "einundzwanzig",
    en: "one Mississippi"
  },
  two: {
    de: "zweiundzwanzig",
    en: "two Mississippi"
  },
  three: {
    de: "dreiundzwanzig",
    en: "three Mississippi"
  }
}
console.table(counting)

Here is the output:

The obvious question: What happens if the object is yet more complex?

console.clear()
var numbers = {
  1: {
    cardinal: {
      de: { "f": "eine", "m": "ein", "n": "ein" },  
      en: "one"
    },
    ordinal: {
      de: { "f": "erste", "m": "erster", "n": "erstes" },  
      en: "first"
    }
  },
  2: {
    cardinal: {
      de: { "f": "zwei", "m": "zwei", "n": "zwei" },
      en: "two"
    },
    ordinal: {
      de: { "f": "zweite", "m": "zweiter", "n": "zweites" },
      en: "second"
    }
  },
  3: {
    cardinal: {
      de: { "f": "drei", "m": "drei", "n": "drei" },
      en: "three"
    },
    ordinal: {
      de: { "f": "dritte", "m": "dritter", "n": "drittes" },
      en: "third"
    }
  }
}
console.table(numbers)

In this case the output in table form isn't very helpful which explains that Object line below the table that I took the liberty to expand.

This much on console.table.

Other Output Methods

There are two additional output methods: console.dir() and console.dirxml(). In the case of an ordinary object the difference between them as well as between them and console.log() is tiny:

console.clear()
var counting = {
  one: {
    de: "einundzwanzig",
    en: "one Mississippi"
  },
  two: {
    de: "zweiundzwanzig",
    en: "two Mississippi"
  },
  three: {
    de: "dreiundzwanzig",
    en: "three Mississippi"
  }
}
console.log(counting)
console.dir(counting)
console.dirxml(counting)

Here is the unexpanded output:

And here is the output after expanding the outermost level:

Things change when you use a DOM element instead. As an example I use the developer tools on http://example.com/ (sic!)

console.clear()
var body = $('body')
console.dirxml(body)
console.dir(body)

The output (for obvious reasons I only show part of it) explains why dirxml has XML in its name.

Debuger

This is not an actual method of the console object but a means to open the console programmatically. When you need to do this simply add this statement to your code:

debugger

String Substitution

console.error(), console.info(), console.log(), and console.warn() support string substitution, i.e. you can add certain symbols to a string that are then replaced by data provided.

Kind of output Substitution symbol
number (as integer) %d or %i
number (as floating point number) %f
string %s
object (object/array) %o or %O

Here is an example of using the substitutions:

console.clear()
console.log(Math.PI)
console.log("Integer part of pi using %%d:  %d", Math.PI)
console.log("Integer part of pi using %%i:  %i", Math.PI)
console.log("Euler's number:                %f", Math.E)
console.log("'Math' as a String:            %s", Math)
console.log("'Math' as an Object using %%o: %o", Math)
console.log("'Math' as an Object using %%O: %O", Math)

The output looks like this:

For more information on string substitution: MDN

Style

console.error(), console.info(), console.log(), and console.warn() support styling of output. Here is a simple example of how you can style console output:

const ERR = 'color: #f66; font-weight: normal;';
const K = 'color: #6f6; font-weight: bold;';
var i, o, s


console.clear()
i = 0;
o = parseFloat(i)
s = Number.isNaN(o) ? ERR : K
console.log('%cParsed %s, got %c%f', '', i, s, o)
i = '0';
o = parseFloat(i)
s = Number.isNaN(o) ? ERR : K
console.log('%cParsed %s, got %c%f', '', i, s, o)
i = 'O';
o = parseFloat(i)
s = Number.isNaN(o) ? ERR : K
console.log('%cParsed %s, got %c%f', '', i, s, o)

And here is the output:

Note that only a (browser-dependent) selection of CSS styles are supported.

Wait, there is more

DOM Elements: $ and $$

The developer tools provide you with two shorthands that simplify getting DOM elements

command shorthand
document.querySelector('element') $('element')
document.querySelectorAll('elements') $$('elements')

XPath: $x

Unleash the power of XPath using $x

$x('//element')

returns an array of elements that match the expression. While this simple example does not do anyting else than $$('element'), it allows to use elaborate XPath expressions.

$x('//div[descendant::span]')

returns the div elements on a page that contain a span element.

Currently Selected Element: $0

To see which DOM element is currently selected you can simply enter $0.

Event Listeners: getEventListeners

To list the event listeners active on a certain DOM element you can use getEventListeners(). Here is a simple example of using it:

console.clear();
getEventListeners($('body'))

And here is its output on https://www.google.de.

js/console.txt · Last modified: 2021/07/25 23:30 by jupp