Firebug and Logging
Your new friend, console.log
The easiest way to write to the Firebug console looks like this:
You can pass as many arguments as you want and they will be joined together in a row, like
Logging object hyperlinks
console.log and its related functions can do a lot more than just write text to the console. You can pass any kind of object to
console.log and it will be displayed as a hyperlink. Elements, functions, arrays, plain ol' objects, you name it. Clicking these links will inspect the object in whatever tab is most appropriate.
console.log can format strings in the great tradition of printf. For example, you can write
console.log("%s is %d years old.", "Bob", 42).
In addition to
console.log, there are several other functions you can call to print messages with a colorful visual and semantic distinction. These include
Timing and profiling
console.time("timing foo") before the code you want to measure, and then
console.timeEnd("timing foo") afterwards. Firebug will then log the time that was spent in between.
console.profile() before the code you want to measure, and then
console.profileEnd() afterwards. Firebug will log a detailed report about how much time was spent in every function call in between.
console.trace() and Firebug will write a very informative stack trace to the console. Not only will it tell you which functions are on the stack, but it will include the value of each argument that was passed to each function. You can click the functions or objects to inspect them further.
Sometimes a flat list of messages can be difficult to read, so Firebug gives you a solution for indenting in the console. Just call
console.group("a title") to start a new indentation block, and then
console.groupEnd() to close the block. You can create as many levels of indentation as you please.
How many times have you hand-written code to dump all of the properties of an object, or all of the elements in an HTML fragment? With Firebug, you'll never write that code again.
console.dir(object) will log an interactive listing of an object's properties, like a miniature version of the DOM tab. Calling
console.dirxml(element) on any HTML or XML element will print a lovely XML outline, like a miniature version of the HTML tab.
Assertions are a wonderful way to ensure that your code stays rock-solid in the face of change. Firebug provides a set of handy assertion functions, and writes very informative error messages to the console when your assertions fail.