JavaScript console tricks

It is generally easier to quickly experiment with PHP or some other language that has an IDE or REPL. However, it is often tricky to quickly test some new JavaScript code or library without first creating a plain HTML page and dropping down to the console.

Chrome developer console however makes it easier to test new libraries or even learn JavaScript if you are a newbie without using something like jsfiddle. Lets say you want to quickly test some jQuery features you like. Instead of creating a web page with the associated jQuery script tag, you can load jQuery from a CDN into the console directly.

var jquery = document.createElement('script');
jquery .src = "";
document.getElementsByTagName('head')[0].appendChild(jquery );

Below is a screenshot of such a debugging session – testing of the jQuery ‘$.each’ utility method.

js sonsole

This will load jQuery in the console and you can now try to test various features of the library. The same applies if you find some new JS library and need to quickly test its features.

Also one other trick I found useful is the ‘console.table()’ method. This displays an object or an array as a table, making it easier while debugging. Imagine you have an array like the following:

var payments = [
  {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"}];

The output of console.log() and console.table() is shown below. You can see how easier it is to visualize the value of the array using the console.table() method.


One thought to “JavaScript console tricks”

Leave a Reply

Your email address will not be published.