Logging for the Lazy
February 11th, 2009
They say that laziness is a virtue in programmers. That is a good sign for me as I am the laziest of them all. When debugging JavaScript in Firefox or Safari, I use console.log all the time. There are two things about console.log that bother me.
Firstly, it is 11 characters. When I just want to output something really quick, it really annoys me that it takes 11 characters just for the function name, not including whatever it is that I want to print out.
Secondly, console.log only takes one argument at a time. More often than not, I’m outputting the values of a few things, which means I have to type (or copy and paste) those 11 characters a lot. What I’ve started doing recently, is adding this simple log function to my projects.
function log() {
if (window && window.console && window.console.log)
for(var i=0, len = arguments.length; i < len; i++)
console.log(arguments[i]);
}
This simple function allows me to do the following:
log(some_var)
log(one_var, two_var, three_var)
It is only 3 characters and allows me to print out as many objects to the console as my heart desires. Nothing fancy, but it gets the job done and saves me some time and thought.
If you enjoyed this post, get free updates by email or RSS.
console.log() can take more than one argument, so if you wanted to be more terse you could go…
log = console.log;
log(’a',’b',’c');
Did I miss something?
@Tim - Huh. I could have swore I tried console.log before with multiple arguments and it didn’t work. Seems to just fine now. I guess I can strip out the for loop. The only other benefit that my log function provides is that if you leave a stray log in your code it won’t cause an error in browsers that do not have console.log as I check for its availability first.
I thought that was a neat little trick there until I noticed what Tim Snadden said, haha. Thanks anyway!