Debugging arrays and objects in JavaScript with the console.table() function
In the first debugging blog post, we’ve learned about the console.log() method and how it works to debug scalar types or arrays. But there is a nicer way to log arrays or objects in the browser.
The console.table() function
As mentioned in the first blog post, the console object has some more useful functions, and today we want to take a look at the table() function.
This is the most basic example. We just use a one-dimensional (numerical) array. This is the result in the browser console:
As you can see here, you get a table with two columns. The first one is the numerical “(index)” for the array, and the second one has the “Value” for each entry of the array. You will still always have the variable below the table, just as with console.log() and you can “expand” it here, to investigate it further.
Multidimensional arrays
The function can not only be used with simple one dimensional array, but you can also use it for multidimensional ones:
That looks nice, right? Except for “(index)”, we have some good columns names and our index values also are not numerical anymore.
Logging only specific columns
The console.table() function has a second parameter columns, which is an array as well. It expects an array with the names of the columns/indices. So for our previous code, we could do this:
And sure enough, this would be the logged results:
(index)
firstName
mother
'Padmé'
father
'Anakin'
daughter
'Leia'
son
'Luke'
Pretty neat, isn’t it? This can be really useful when debugging some larger objects with multiple properties.
Conclusion
Even though you can use the generic console.log() function to debug and log arrays and objects, seeing them in a logged table, can make reading them a lot easier. You also don’t have to “expand” the tables.