Introduction
Hello everyone! Today, I'd like to share some lesser-known features and usage methods of console
object, that I recently learned about. Probably you're already familiar with how to use console.log
. But in this article, I'll introduce you to some unique ways to leverage console
method.
While these may not be essential for practical use in your programming situation, but they can be interesting. Feel free to give them a try!
Adding Styles
Do you know that you can add styles to console.log?
You can add styles to your console output using the %c
format specifier in the first argument of console.log. You can customize the appearance of the text by setting the color, font size, etc. This is the example:
console.log("%c This is styled text", "color: blue; font-size: 18px;");
Here is an example of using a function to display a random color:
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
console.log("%c It's random color block", `font-size: 16px; padding: 5px; color: #fff; background-color: ${getRandomColor()};`);
You can play this in the browser console without preparing a code editor. Please give it a try!
Grouping with console.group + console.groupEnd
You can organize your logs by grouping them together. This is especially handy when dealing with complex code. Use console.group
to start a group and console.groupEnd
to close it. Here is example:
console.group("Group 1");
console.log("Log 1");
console.log("Log 2");
console.groupEnd();
If you look at the console, you will see that nesting is generated and Log 1
and Log 2
are stored inside. I can't think of a scenario where this would be useful, but it might be useful to organize in certain situations.
Tabular Display with console.table
When dealing with arrays or objects, use console.table
for a neat tabular display:
const data = [
{ name: "Takeshi", age: 29, profession: "Baker" },
{ name: "Jane", age: 33, profession: "Teacher" },
];
console.table(data);
If you look at the console, you will see that the table has been generated. I honestly could not think of any scenario where this one could be used, but I thought it was unique and interesting.
Conclusion
In my case, I often use console.log
for debugging and checking the behavior of my code but I didn't know adding style to console, console.group and console.table until recently. When I first learned about these methods, I found them intriguing. While I couldn't immediately think of practical scenarios to use them in my everyday work, but I found them unique and enjoyable. I hope you enjoyed these too!
Thank you for reading.
Top comments (0)