Posts Tagged ‘console.log’

Immunodeficiency

Tuesday, January 26th, 2010

I just solvedĀ  a bug which stemmed from the fact I forgot that javascript is a referential language, i.e. if you have a variable and you set another variable equal to it then it doesn’t in general clone the original variable, but merely just points both variables towards the same underlying object. This only applies to Arrays and Objects though, and to prove it here is a little demo (it turns out you can embed javascript straight into wordpress posts now!)

Irritatingly, if you have a bug which is caused by forgetting this principle then this will also make it hard to debug because it also affects how firebug reports information to you. When you console.log() an object or an array, firebug does the same as javascript – it creates a reference to an underlying object in the DOM. So, if you’ve been logging an object repeatedly in order to pinpoint when a rogue change takes place firebug will consistently provide you with references to the object as it is after your script’s finished running – not much use.

However, there is an easy way out*. console has methods other than .log(), and possibly the most useful is console.dir(). console.dir() takes a snapshot of any object or array, printing out each of its properties without maintaining a reference to the underlying object, and therefore giving a you a snapshot of an object as it is at the time.

*And a hard way (console.log() the properties of an object individually), which is how I resolved my bug, beforeĀ  looked into what other methods console had

But it works for me!!!

Monday, November 16th, 2009

The lines of javascript below, included at the top of your scripts, could save you a lifetime of confusing conversations with clients where they say an application doesn’t work and you can clearly see that it works on your laptop.

The difference is that you have firebug installed and they don’t, so for you console is defined, but for them it is not, so if you leave any references to it in the app it will throw an error for them. But this fixes that;

if(!console) {
 var console = {};
 console.log = function() {
   return null;
 };
}