FrontendWalla

Solutions for Real World Frontend Problems.

Debugging Javascript using Console Object

Some of you might have already used  Console Object in javascript to log values of a variable for debugging purposes.


var arr = [‘1′,’2′,’3′,’4′,’5’];
console.log(arr);

There are some interesting methods in Console API other than log. The details of Console API can be found  here https://developers.google.com/chrome-developer-tools/docs/console-api

Note: The link above is for Console API supported by Chrome.

But some of interesting one I would like to mention here are:

1. console.profile();  which is used along with console.profileEnd();

function processPixels() {
  console.profile("Processing pixels");
  // later, after processing pixels
  console.profileEnd();
}

This is used for profiling of time that a method is taking.

2. console.trace(); 

Prints a stack trace from the point where the method was called, including links to the specific lines in the JavaScript source.

3. console.table();

Prints a javascript array or Object in Tabular Format.

It should be noticed that Console Object is not available in all browsers and though debugging javascript with Console Object is Quite Helpful if you forget to remove your Console statements it will give you errors in unsupported browsers.

It can also be possible that you don’t want to remove the console Statements so that you can always debug your application.

For this a small code that will take care of all the console.log Statements can be added..



if (typeof console === 'undefined')) var console = { log: function() {} };
It should be noted that the above function takes care of console.log statements only. If we are using other console functions than it should be entered in the console object similiar to the way log function is added.

Debugging Javascript using Console Object

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top