This post was inspired by "How to use console command effectively" in which Trishul presents some effective methods of using console logging. Read that post to learn about various logs, styling, time
, assert
, and count
.
How to use console command effectively
Trishul for Itsopensource ・ Jun 24 '20 ・ 2 min read
I want to add a couple more to that list that I found useful in my career:
- groupCollapsed
- table
- the combination of groupCollapsed + table
console.groupCollapsed
Let's say you have a function that is doing something on every link on a webpage. For debugging purposes, you are logging every time it does its thing:
const showLinks = () => {
const links = [...document.querySelectorAll('a[href]')];
links.forEach(el => {
console.log(el.href);
});
}
Some websites have a lot of links, so to not pollute console too much, you can encapsulate those logs under an expandable group.
console.groupCollapsed('Links')
showLinks();
console.groupEnd('Links');
What's important here is where you execute the function, not where it is defined.
Result:
Expanded (for an MDN website, cut off, because there were too many links to fit on the screen):
console.table
Table is a console tool that allows you to display structured data in a visually pleasing way.
Logging collections:
const cars = [
{ maker: "Honda", model: "CRX", year: 1989 },
{ maker: "Opel", model: "Corsa", year: 1998 },
{ maker: "Honda", model: "Civic", year: 1999 },
{ maker: "Subaru", model: "Forester", year: 2006 },
{ maker: "Peugeot", model: "406", year: 2001 },
]
console.table(cars);
Results:
You can decide which column should be logged:
Logging plain arrays (including nested):
Combining groupCollapsed and table
You can even use them in tandem, which is pretty nice if you use logging extensively:
const cars = [
{ maker: "Honda", model: "CRX", year: 1989 },
{ maker: "Opel", model: "Corsa", year: 1998 },
{ maker: "Honda", model: "Civic", year: 1999 },
{ maker: "Subaru", model: "Forester", year: 2006 },
{ maker: "Peugeot", model: "406", year: 2001 },
{ maker: "Honda", model: "CRX", year: 1989 },
{ maker: "Opel", model: "Corsa", year: 1998 },
{ maker: "Honda", model: "Civic", year: 1999 },
{ maker: "Subaru", model: "Forester", year: 2006 },
{ maker: "Peugeot", model: "406", year: 2001 },
{ maker: "Honda", model: "CRX", year: 1989 },
{ maker: "Opel", model: "Corsa", year: 1998 },
{ maker: "Honda", model: "Civic", year: 1999 },
{ maker: "Subaru", model: "Forester", year: 2006 },
{ maker: "Peugeot", model: "406", year: 2001 },
]
console.groupCollapsed('Cars');
console.table(cars);
console.groupEnd('Cars');
Results:
Expanded:
Happy logging!
Read more
If you are interested in more performance oriented content, follow me and I promise to deliver original, or at least effective methods of improving your website.
Top comments (0)