This is the P2PU Archive. If you want the current site, go to www.p2pu.org!

jQuery ~ For the Love of Dollar

My recent threads

You haven't posted any discussions yet.

Recently updated threads

why console.log()

Go back to: General discussion

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.

Frankie Yan's picture
Frankie Yan
Fri, 2011-02-04 10:16

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.

Dan Diebolt's picture
Dan Diebolt
Fri, 2011-03-04 07:47

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.

Herbert Nerder's picture
Herbert Nerder
Fri, 2011-02-04 14:47

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.

John Gillespie's picture
John Gillespie
Fri, 2011-02-04 18:42

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.