Archive for November 2013

Debug javascript in smarter way console.table()

by in 0

Works in Chrome and Firefox
Via mariusschulz.com

LOGGING ARRAY DATA WITH CONSOLE.LOG()

Imagine you have created this list of programming languages and their file extensions:
var languages = [
    { name: "JavaScript", fileExtension: ".js" },
    { name: "TypeScript", fileExtension: ".ts" },
    { name: "CoffeeScript", fileExtension: ".coffee" }
];

console.log(languages);
The console.log() call will give you the following representation of your data:
Console Output for console.log
That tree view is helpful for debugging purposes, but I find it a little cumbersome to have to open every collapsed object manually. I'm saying we can do a little better withconsole.table().

LOGGING ARRAY DATA WITH CONSOLE.TABLE()

Instead of calling console.log(), we'll use console.table() now:
console.table(languages);
Make sure the console is opened before refreshing the page, otherwise you won't see any output. If you did everything correct, you'll be rewarded with this nice, little table view:
Console Output for console.table()
Pretty neat, isn't it?
Of course, tables work best for tabular data. If all the objects have a totally different structure, you'll end up with most of the cells containing undefined values. Still, the property values are neatly arranged and give you a good overview.

LOGGING OBJECT DATA WITH CONSOLE.TABLE()

Another nice thing about console.table() is that it also works with objects:
var languages = {
    csharp: { name: "C#", paradigm: "object-oriented" },
    fsharp: { name: "F#", paradigm: "functional" }
};

console.table(languages);
Console Output for console.table() called with an object
'nuff said.

FILTERING THE DISPLAYED OBJECT PROPERTIES

If you want to restrict the columns to certain properties, you can pass an array of their keys as a second parameter to the console.table() call:
// Multiple property keys
console.table(languages, ["name", "paradigm"]);
For a single property, a simple string is sufficient:
// A single property key
console.table(languages, "name");Via mariusschulz.com