Saturday, October 08, 2011

JavaScript: use power of console

console.log() - is pretty nice way to display debug information without interrupting user's actions. But do you know that 'console object' has lot of other useful methods? In this article I will try to show another important method in console object.


1. power of output
most common case for using console object is:
console.log("hello word")
but here few more ways how we can use it
console.log("string1", "string2", 1, 2, {proper1:"val1", proper2: 5});
console.log("Do you know that word %s same for all language except english %s. %d < %d", "ananas", "pineapple", 1, 2);
There are few another kind of log (works same as log but has different status)
console.debug(), console.info(), console.warn(), console.error()


console.group() and console.groupEnd() allow you to format very nice output with categories, it is very usefull when you have tons of data in log so you can easy control what is related to etc.
console.group("Food")
console.group("Fruit")
console.log("Apple")
console.groupEnd("Fruit")
console.group("Vegetables")
console.log("Potato")
console.groupEnd("Vegetables")
console.groupEnd("Food")
2. power of time
just put console.time()/console.timeEnd() before/after code where you want to measure time .
Aslo there are profile methods console.profile() and console.profileEnd() which allow to see "stack".


3. power of inspection
I guess most of us often want to see specific properties in HTML fragment, for such tasks we can use console.dir(object) or console.dirxml(element)


Some usefull articles about logging: Firebug about logging and Joe Hewitts about console

No comments :