To make debugging easier, we can display an object we want to inspect in the console.
There are various ways to do this.
In this article, we’ll look at how to display a JavaScript object in the browser console.
console.log
The console.log
method will log an object’s content directly to the console.
For instance, we can write:
const obj = {
a: 1,
b: 2,
child: {
c: 3
}
}
console.log(obj)
We just pass in obj
into console.log
to log its content directly to the browser’s console.
JSON.stringify
The JSON.stringify
lets us convert a JavaScript object into a JSON string.
For instance, we can write:
const obj = {
a: 1,
b: 2,
child: {
c: 3
}
}
const str = JSON.stringify(obj);
console.log(str)
Then we see:
{"a":1,"b":2,"child":{"c":3}}
in the console.
To make reading it easier, we can add indentation to the properties that are stringified.
To do this, we write:
const obj = {
a: 1,
b: 2,
child: {
c: 3
}
}
const str = JSON.stringify(obj, undefined, 2);
console.log(str)
The 3rd argument of JSON.stringify
specifies the indentation of each stringified.
2 means 2 spaces.
So we should get:
{
"a": 1,
"b": 2,
"child": {
"c": 3
}
}
logged into the console.
The console.dir Method
The console.dir
method also logs an object into the console like console.log
.
For instance, we can write:
const obj = {
a: 1,
b: 2,
child: {
c: 3
}
}
console.dir(obj)
to log obj
into the console.
The console.table Method
The console.table
method lets us log an object’s properties in a tabular format.
For instance, if we write:
const obj = {
a: 1,
b: 2,
child: {
c: 3
}
}
console.table(obj)
Then we get a table with the properties and values of an object in a table.
Conclusion
Browsers come with many methods to log objects into the console.