In this post we'll also learn more about Logging in JavaScript. This post is for everyone who wants final guide to Logging in JavaScript.
The console is part of the window object that gives you access to the browser's console. It lets you output strings, arrays and objects that help debug your code.
We can get access to the console on one of two ways:
window.console.log("Hello World!");
console.log("I'm sammy");
// Hello World
// I'm sammy
The most common element of the console object is console.log()
. For most scenarios, you'll use it to get the job done.
There are four different ways of outputting a message to the console:
Where console.error
and console.warn
out puts to stderr, the other output to stdout.
With the console object and its logging methods, long are the days of calling alert()
to debug and get a variable's value.
Besides the general logging methods that we have discussed in the previous part, there are few more methods that we can play around with.
Now we will cover:
- Stack tracing
- Asserting
Stack tracing
The console.trace()
method displays a trace that show how to code ended up at certain point.
Take a look at the below example, to understand how console.trace()
works.
function hey(name) {
console.trace('name:', name);
return `Hello ${name}!`;
}
hey('sammy');
// OUTPUT
// "Hello sammy!"
Asserting
The console.assert
method is an easy way to run assertion tests. If the assertion of the 1st argument fails, the subsequent argument gets printed to the console.
Let's look at this example,
// this will pass, nothing will be logged
console.assert(1 == '1', '1 not == to "1"');
The below assertion fails,
// this will pass, nothing will be logged
console.assert(1 === '1', '1 not == to "1"');
Output:
Assertion failed: 1 not == to "1"
Formatting Logs
There is a way to print out objects in a nice formatted way using console.dir()
.
For example:
const sammy = {
topic: 'Logging',
platform: 'Javascript',
date: {
year: '2020',
month: 'March',
day: 'Saturday'
}
};
console.dir(sammy);
You can print out a DOM element's markup in a formatted way using console.dirxml()
.
for example:
<body>
<h1>Hey</h1>
<script>
console.dirxml(document.body)
</script>
</body>
The same will be the output 😅
Countings
The console.count()
method is used to count the number of times it has been invokedd with the same provided label.
For example, here we have two counter, one for even values and another on for odd values.
[1, 2, 3, 4, 5].forEach(nb => {
if (nb % 2 === 0) {
console.count('even');
} else {
console.count('odd');
}
});
Clearing the logs:
You can clear out all the console logs using the console.clear()
method.
Record Timings
You can record how long an operation took to complete using console. You can start a timer with console.time
and then end it with console.endTime
.
For Example:
console.time('timer');
setTimeout(() => console.log, 1000);
console.timeEnd('timer');
// timer: 0.123945114ms
Note: Passing the label in console.time is optional. If you use a label with console.time
you must pass-in that same label when calling console.timeEnd
.
Grouping logs
You can group the console messages together with console. Use console.group
and console.groupEnd
to group console messages together.
For Example:
console.group('Even Numbers');
console.log(2);
console.log(4);
console.log(6);
console.groupEnd('Even Numbers');
Nested grouping logs
Groups ca also be nested to another one. Take a look at the below example,
console.group('Even');
console.log('2');
console.group('Odd');
console.log('1');
console.log('2');
console.groupEnd();
console.log('6');
console.groupEnd();
Styling your logs:
Console logging can be styled using the delimiter %c
. The first argument is the message to displayed. Everything that comes after the first %c
will be styled by the string provided by the secong argument, then everything after the next %c
is styled by the following string argumnet, and so on.
console.log(
'Hello %csammy%c!',
'color: blue; font-weight: bold; font-size: 1rem;',
'color: hotpink; font-weight: bold; font-size: 1rem;'
);
Tabular visualization of logs
The console.table()
allows to display data in the console in a nice tabular format.
const jsonData = [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
}
];
console.table(jsonData);
Any type of JSON can be represented in a tabular view. You can display an Array in a tabular view
const y = [
["One", "Two"],
["Three", "Four"]
];
And, you can also display an object in a tabular view. You may wonder how? Take a look at this example.
const x = { a: 1, v: { a: 1 } };
console.table() displays nay object data in a tabular view. But, if a JSON has multiple nested objects inside, it just prints the root level objects in the tabular view.
Let's see that in this example:
const x = [
{ p: 123, i: 1 },
{
p: 124,
i: 2,
x: {
a: 1,
b: { s: 23 }
}
}
];
Sorting in logs
console.table()
comes with an inbuilt sorting. Yoou can sort the table by a particular column by clicking on that column's label.
const y = [
["One", "Two"],
["Three", "Four"]
];
console.table(y);
⚡Thanks For Reading | Happy Coding🚀
Top comments (0)