This is the P2PU Archive. If you want the current site, go to www.p2pu.org!
You haven't posted any discussions yet.
Hi all
I have been reading the JQuery html book. I notice there is a lot of console.log() in the examples. I know what it does and I tried it with firebug. But I am just wondering what the practical use of console.log is. Why do I need to write stuff to the console.
For debugging purposes, say you want to find out what value a variable is holding, or print a message when some particular step in the script has been executed, etc. It's just a cleaner way of doing it compared to using alert boxes.
alert() takes a string argument while console.log can take any object or primitive datatype and produce a human readable format. Try
console.log(["cat","dog","hampster"]);
console.log({pet: "dog", age: 23});
console output:
["cat", "dog", "hampster"]
Object { pet="dog", age=23}
For complex objects with several levels of containment, console.log produces a click-able tree of object keys and property values.
The only reason you should be using alert() is if you are demonstrating something and you have no control over the browser or addons installed. alert() will always be available as it is part of JavaScript.
If you insist on using alert in other scenarios, redefine it as follows:
alert=console.log
On other matters, we have moved to Google Groups for our discussions to please continue discussions there.
On the issue of "redefining", I recently noticed a little gem by Paul Irish in the HTML5 Boilerplate:
http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
I haven't started using it yet, but it makes sense.
console.log('Oops') = fputs(stderr,'Oops\n') = write (1,'(A)')'Oops'
In the absence of a debugger, it is the only way to examine the inner workings of your code.
With a debugger (like firebug for Firefox, or MS Visual Studio, or the built-in debuggers in Chrome, Safari), you don't need it.
BTW, if you are on a Mac and want to access the debugger menu that includes javascript debugging, enter the following in a terminal window when Safari is not running:
defaults write com.apple.Safari IncludeDebugMenu 1
This appears to be the same debugger used by Chrome, so I infer it is part of the webkit both use.