Categories
JavaScript Tips&Tricks

console.log in JavaScript – Tips & Tricks

One of the most used feature in JavaScript is console.log(), especially for debugging. Even though it is widely used most of the time we do not utilize all the power and possiblities of console.log().

console.log

This is the most famous and most popular way of logging, even though we have some more ways, but let’ s explore this. We can console.log a message, or we can console.log variable, or both. Check the example below.

/**
 * Let's say we have an array that we want to debug 
 */

const arr = [1, 2, 3, "webinuse", "Twitter", "test", 4, 5];



/**
 * If we just console.log the array, console will output array  
 */
 
console.log(arr)
//Output: (8) [1, 2, 3, "webinuse", "Twitter", "test", 4, 5]



/**
 * We can also have message that goes with that console.log
 */

console.log("This is our array", arr)
//Output: This is our array (8) [1, 2, 3, "webinuse", "Twitter", "test", 4, 5]


/**
 * If we put array in the first place, 
 * and message in second, than our message will 
 * not be treated as message but as String
 */
 
 console.log(arr, "This is our array");
 //Output: (8) [1, 2, 3, "webinuse", "Twitter", "test", 4, 5] "This is our array"

console.dir

If we want to log HTML element we can use console.log or console.dir. console.log prints the element in an HTML-like tree, while console.dir prints the element in a JSON-like tree. Also, console.log prints tree of HTML elements, while console.dir prints interactive list of the properties of the specified JavaScript object.

/**
 * We can use console.log to log HTML elements
 */
 
 console.log(document.body);
 //Output: <body class="a b c">...</body>
 
 
 
 /**
  * We can use console.dir to log HTML elements. 
  * But insted of HTML console.dir will log 
  * interactive list of the properties of the specified JavaScript object
  */
  
 console.dir(document.body);
 /**
  * Output: body.a.b.c
  *             aLink: ""
  *             accessKey: ""
  *             ariaAtomic: ""
  * ................................
  */

There is also console.dirxml, as per MDN, that displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead.

console.dirxml(document.body);
/**
 * Output: 
 * <body class="a b c">...</body>
 */

console.assert

Console.assert will print ERROR to the console only if certain assertion is false.

const errorMsg = 'the # is not even';
for (let number = 2; number <= 5; number += 1) {
    console.log('the # is ' + number);
    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
    // or, using ES2015 object property shorthand:
    // console.assert(number % 2 === 0, {number, errorMsg});
}

// output:
// the # is 2
// the # is 3
// Assertion failed: {number: 3, errorMsg: "the # is not even"}
// the # is 4
// the # is 5
// Assertion failed: {number: 5, errorMsg: "the # is not even"}

console.count

The console.count() method logs the number of times that this particular call to count() has been called.

Also, we can use console.countReset() to revert count to zero for that particular instance. Check out example.

/**
 * Count how many times function has been called
 */
let user = "";

function greet() {
  console.count();
  return "hi " + user;
}

user = "bob";
greet();
user = "alice";
greet();
greet();
console.count();
//Output
// "default: 1"
// "default: 2"
// "default: 3"
// "default: 4"

console.countReset();
// "default: 0"

/**
 * Count how many times function has been called
 * for certain label
 */


let user = "";

function greet() {
  console.count(user);
  return "hi " + user;
}

user = "bob";
greet();
user = "alice";
greet();
greet();
console.count("alice");
//Output
// "bob: 1"
// "alice: 1"
// "alice: 2"
// "alice: 3"

console.countReset("alice");
// "alice: 0"

console.debug

This method is same as console.log with the exception that it has to be enbaled in your browser. Normally you enable it in console under log level ‘Debug’ or ‘Verbose’

console.error

console.error prints ERROR like messages to your console. It is great for debugging errors of any type like: fetch error, API response error, etc. It recieves same parameters as any other console log method.

Created simple object and then it was logged to console along with some message using console.error()

console.group

Creates inline console group, until it’s terminated by console.groupEnd().

Example of creating groups of logs in console, using console.group

console.info

Console.info is same as console.log, even got the same look.

console.table

Console.table is one of the most unused logging methods. It helps us sort our data in table like structure, so it is easier to see what we’ re dealing with.

Example of logging data to the console using console.table

console.time

Console.time methods are the best way to measure performance of certain function, or to measure some other type of time.

// First we have to create timer and start it
console.time("test")

//Then, when ever we want we can check for the status 
//of created timer(s)
console.timeLog("test")

//Then, when we want we can stop timer, a log the time
console.timeEnd("test")
Example from code snippet used in console

console.trace

The console interface’s trace() method outputs a stack trace to the Web Console. Check out Stack Traces in console on MDN.

function foo() {
  function bar() {
    console.trace();
  }
  bar();
}

foo();

/**
 * Output 
 *  bar
 *  foo
 *  <anonymous>
 */
 

console.warn

Console.warn outputs warning message to the console. Can be pretty useful while developing application as message for developers. If you have ever worked with ReactJS you would be familiar with those messages.

Warning example

If you have any questions or anything you can find me on my Twitter, or you can read some of the older articles like How to select element(s) using vanilla JavaScript?