JavaScript
How to console log better in JavaScript
Updated:
You are probably already very familiar with using console.log()
to print something to the console, especially the browser console. While this method is handy, there are lots of other methods on the console
object that can make debugging, and our lives, for that matter, much easier.
console.table()
Let's say we are retrieving a list of users from an api:
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((json) => console.log(json));
Our response looks like this:
We can display this data in a more readable table format with the following:
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((json) => console.table(json));
Now our response looks like this:
What if we are only interested in seeing specific pieces of data? We can pass an array to the console.table()
method with the keys we are interested in, like so:
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((json) => console.table(json, ["username", "email", "phone"]));
Now our response looks like this:
console.log() - with custom styles
When logging something to the console, it can sometimes be hard to differentiate between what you are logging, and everything else. We can solve this by passing custom CSS to our console.log()
to make it stand out.
console.log("%cTest", "background-color: green; padding: 10px");
Now our console.log()
looks like this:
or:
console.log(
"%cError",
"background-color: red; padding: 10px; border: 5px solid white; color: black;"
);
Looks like:
console.dir()
This is another helpful method that allows you to navigate large JS objects better.
From the MDN docs:
The Console method dir() displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.
In other words, console.dir() is the way to see all the properties of a specified JavaScript object in console by which the developer can easily get the properties of the object.
console.dir(document.location);
Looks like this:
console.error()
Another simple method on the console
object is console.error()
this outputs a message formatted as an error.
console.error("there has been an error...");
Looks like this:
console.debug()
Another simple method on the console
object is console.debug()
this outputs a message formatted as a debug message.
console.debug("this is a debug message...");
Looks like this:
console.warn()
Another simple method on the console
object is console.warn()
; this will output a message formatted as a warning.
console.warn("this is a warning message...");
Looks like this:
Wrap up
You can find all the console
methods over at the MDN Docs