[object Object] in JavaScript
Posted
console.log
is the bread and butter of debugging your JavaScript code. But it’s not uncommon to try to console.log
an object and you see [object Object]
. I was wondering why is this happening so I researched it a bit and here is what I found.
[object Object]
is the string representation of any object. You see it in console or on your screen because you have invoked Object’s toString
method. Here are a couple of common situations when this happens.
When You Concat an Object to String
This one is one of the most common cases when this happens. It usually happens when people forget to put a comma between string and object like this.
const exampleObject = {a: 1};
console.log('Example Object is: ' + exampleObject);
This way you get Example Object is: [object Object]
;
Solution?
Put a comma between your string and object or use JSON.stringfy
method.
const exampleObject = {a: 1};
console.log('Example Object is: ', exampleObject);
When Printing Result From an API
Let’s say you want to organize your day a bit you build a TODO API (yeah, I know). You hear a lot of great things about this new fetch
API. You build your backend and now switch over to frontend and you want to test your API.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log(res))
Now you might get two results. Either [object Object]
or [object Response]
. But it’s not definitely what you wanted.
If you want to fix this add another then after fetch
call where you return JSON value of the response.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(res => console.log(res))
When Alerting an Object
You might not be a fan of console
. You prefer to use alert
. But every time you try to alert
an object you get something like this:
If you checkout alert
documentation, you will notice that alert()
takes one argument of type string
so when you are calling alert(object)
you are actually calling alert(object.toString())
.
Solution?
Pass JSON.stringy(obj) instead of just obj to alert.
const exampleObject = {a:1};
alert(JSON.stringfy(exampleObject));
Conclusion
Although not one of my lengthiest articles, I hope this article saved you a couple of hours of pulling your hair out (speaking from personal experience).
In conclusion, when printing an object try using JSON.stringfy
or if you want to print it in console, use console.table
instead of console.log
.