Mastering Javascript console methods

Console object in Javascript provide access to the web browser’s debugging console. This article explains how to use each method in detail.

  • console.assert – writes an error message to the console if the assertion is false.
Syntax : console.assert(expression, message)
let x = 10;
console.assert(x<10, 'X is greater or equal to 10');
  • console.clear – clears the console.
console.clear();
  • console.count – logs the number of times called this method. optionally you can pass a label to count specific method.
console.count();
  • console.debug – outputs a message to the web console at the “debug” log level.
Syntax : 
console.debug(obj1 [, obj2, ..., objN]);
console.debug(msg [, subst1, ..., substN]);
  • console.dir displays an interactive list of the properties of the specified JavaScript object.
let x = {model: 'Audi', color: 'white'};
console.dir(x);
  • console.error – Outputs an error message to the Web Console.
console.error("test is an test error");
  • console.info – outputs an informational message to the Web Console.
console.info("Hello world!");
  • console.log – outputs a message to the Web Console. By adding ‘%c’, you can style the output with CSS. Also, if you wrap an object with {}, it will print object name also.
let x = {y: 10};
let z = 'test';

console.log(x, z);
console.log({x});
console.log('this is a test');
console.log('%c Hello world', "color: blue; font-size: 24px;");
  • console.warn – Outputs a warning message to the Web Console.
  • console.table – displays data as a table
var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]]
console.table(people);
  • console.timer – Starts a timer.
Syntax : console.time(label);
console.time('my timer');
  • console.timerLog – Logs the current value of a timer already running.
Syntax : console.timeLog(label);
console.timeLog('my timer');
  • console.timeEnd – Stops the given timer.
console.timeEnd('my timer');
  • console.trace – outputs a stack trace to the Web Console.
console.trace();

For more info: https://developer.mozilla.org/en-US/docs/Web/API/console

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.