Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

JavaScript development in the browser console

Posted: August 10, 2014
Written by: Saints At Play
Category: Javascript

One of the great things about modern website development is the range of tools available to developers and nowhere is this truer than within modern website browsers. In fact, one of the most powerful and often under-utilised tools is that of the browser console.

The Console API provides developers with a range of powerful tools through which to develop, debug and test their JavaScript code to a level that simply wasn't available a decade ago. With that in mind, let's take a look at some of the options available with the Console API.

console.log()

Any front-end developer who's acquainted with basic JavaScript will be familiar with using the console.log() method. By adding this method into our scripts we can display unobtrusive messages within the browser console during the development/testing phases of a project, for example:

var countryNames = ['Australia', 
                    'Barbados', 
                    'Canada', 
                    'Denmark', 
                    'England', 
                    'France', 
                    'Germany', 
                    'Holland'];
for(var j = 0; j < countryNames.length; j++)
{
 console.log('Country is: ' + countryNames[j]);
}

// Returns 
Country is: Australia
Country is: Barbados
Country is: Canada
Country is: Denmark
Country is: England
Country is: France
Country is: Germany
Country is: Holland

Definitely better than the 'good' old days of using alert boxes to test/return back our data right? ;)

Okay, nothing particularly spectacular about the above despite its usefulness. Now let's see how we can extend this method to leverage even greater use from it.

One of the nice things about the console.log() method is that it can accept arguments and additional parameters. For example, we can pass in different objects, such as strings, integers, floats and arrays and they will be displayed as a space delimited string in the browser console:

console.log('A', 'B', 'C', 1, 2, 3, 1.1, 2.2, 3.3, ["Title #1", "Title #2", "Title #3"]);

// Returns
A B C 1 2 3 1.1 2.2 3.3 [" Title #1", " Title #2", " Title #3"]

We can also use format specifiers to control how the output is displayed.

A format specifier is composed of a string beginning with a percentage sign followed by a letter that defines which formatting will be applied to the subsequent browser console output.

For example:

console.log("Page head tag: %O", document.getElementsByTagName("head"));

In the above code snippet we have instructed the console.log() method to format the value of the specified HTML element as an expandable JavaScript object (through use of the %O format specifier) which gives us the following output:

Console log Object

If we modify this snippet by using a lowercase o in the format specifier:

console.log("Page head tag: %o", document.getElementsByTagName("head"));

The browser console formats the value as an expandable DOM element instead:

Console log method HTML object

Compatible with: Firebug, Google Chrome, Safari, Opera, Internet Explorer 10+

console.dir()

This particular method allows the developer to display a list of all the properties associated with a specified JavaScript object making the debugging and inspection of dynamically generated objects (I.e. when parsing external data into custom objects for later read/write operations) quicker and easier to accomplish.

Simply enter the name of the generated object between the parentheses of the console.dir() method like so:

console.dir(generatedObjectNameHere);

And you will see browser console output similar to the below:

Console directory method results

Here each object is able to be expanded revealing the key/value pairs contained within - making this a pretty damn useful method if you need to understand how your JavaScript objects are performing.

Interestingly you can achieve the same result with use of the %O format specifier in the console.log() method like so:

console.log("%O", generatedObjectNameHere);

Which returns the exact same structure and output:

Console log results

Compatible with: Firebug, Google Chrome, Safari, Opera, Internet Explorer 10+

console.dirxml()

Similar to console.dir() this method allows developers to print to the browser console the source tree of an XML or HTML file. If we wanted to output the results of the html <head> tag with the console.xmldir() method we could do the following:

console.dirxml(document.getElementsByTagName("head"));

The output is almost identical to that of the console.log() method when using the %o format specifier:

Console dirxml method results

Compatible with: Firebug, Google Chrome, Safari, Opera, Internet Explorer 11+

console.table()

An alternative way of formatting the display of data to be output in the console window is to use the console.table() method. This accepts 2 parameters - the data to be formatted and the number of columns the table will use, for example:

console.table(dataTobeUsed, 15);

Which, based on the data supplied, outputs the following:

Console table results

The data is formatted and output in a JavaScript array structure with each array element able to be expanded for further inspection.

Compatible with: Firebug, Google Chrome, Safari

console.time()

The console.time() method starts a timer with a name supplied between the parentheses which (along with the console.timeEnd() method) can be used to test certain script methods to help identify any performance concerns with execution times.

Simply supply the script that you wish to test between the console.time() and console.timeEnd() methods and, assuming there are no mistakes with the code to be run, you will see the execution time of that script being logged to the console window.

If, for example, we wanted to test the execution time of a floating-point conversion method we could do something like this:

console.time("Testing floating-point conversion");
parseFloat(931.175.toPrecision(2));
console.timeEnd("Testing floating-point conversion");

// Result
Testing floating-point conversion: 0.044ms

Compatible with: Firebug, Google Chrome, Safari, Internet Explorer 11+

console.timeEnd()

The console.timeEnd() method is used to stop a timer that was called with the console.time() method and prints the elapsed time to the console window (refer to previous example). The same name that was used in console.time() must be called with this method to stop the timer that was created.

Compatible with: Firebug, Google Chrome, Safari, Internet Explorer 11+

console.group

The console.group() method allows scripts to be grouped together in blocks, with each block able to be identified by a unique name supplied in the parentheses of the method.

Each block needs to be terminated with the console.groupEnd() method which calls the name of the block to be closed within its parentheses.

For example:

console.group("Floating point conversion method #1");
console.time("toPrecision method");
parseFloat(931.175.toPrecision(2));
console.timeEnd("toPrecision method");
console.groupEnd("Floating point conversion method #1");

console.group("Floating point conversion method #2");
console.time("toFixed method");
parseFloat(Number(931.175).toFixed(2));
console.timeEnd("toFixed method");
console.groupEnd("Floating point conversion method #2");

console.group("Floating point conversion method #3");
console.time("Advanced method");
Math.round(parseFloat((931.175 * Math.pow(10, 2)).toFixed(2))) / Math.pow(10, 2);
console.timeEnd("Advanced method");
console.groupEnd("Floating point conversion method #3");

Which outputs the following result to the Console:

Console group end results

Compatible with: Firebug, Google Chrome, Safari, Internet Explorer 11+

console.profile()

A more effective measure for testing script execution time involves using the console.profile() and console.profileEnd() methods.

These methods call the browser's JavaScript profiler to return detailed results of a script's performance to the console window. The results that are returned include the functions that were called, how many times those functions were called, which libraries were used and the times involved at each step of the profiler.

Unlike the console.time() and console.timeEnd() methods these don't require named parameters within the parentheses, simply include them in your scripts like so:

console.profile();
method1();			
method2();
console.profileEnd();

In Firebug, for example, these console methods returned the following results for a block of code being tested:

Console profile results

This method of testing script execution times provides a much more detailed breakdown and summary of the different processes being triggered and how long they take to complete.

The only downside with this method of the Console API is that you cannot measure code that isn't a function. To do that you can use the console.time() and console.timeEnd() functions instead.

Compatible with: Firebug, Google Chrome, Internet Explorer 10+

console.trace()

What if you want to see a trace stack of JavaScript functions that have been executed at a particular point in your script? Simple - use the console.trace() method.

console.log("Start tracing stack calls"); // Provide a label for our stack trace
console.trace();
// Rest of JavaScript functions here

Which, depending on what functions you are testing and at what point in your script, will return output similar to the following:

Console trace results

Each function call listed in the trace stack is able to be expanded and clicked onto in order to view its source in the file from where it originates.

Compatible with: Firebug, Google Chrome, Safari, Opera, Internet Explorer 11+

Wrapping up

As you can see the Console API is very powerful and flexible, providing lots of options for developers to test and debug their scripts in the browser window. In the above we've only touched upon a handful of the methods that are available.

For further information on all of the methods that can be used, on a browser-by-browser basis, visit the following links:

« Return to Posts

Comments

There are no comments

Posting comments after three months has been disabled.