What exactly is [object, Object] in JavaScript?
As a Newbie in JavaScript, you must have came across the [object, object]
output in console log or on the view. Ever wondered what that means? Is it an error for logging Object? Or will it break the application?
Well, It isn’t an error, or it won’t break the application either.
[object, Object]
is the string representation of the Object in JS.
It means whenever you are trying to print Object as a string, it will display [object, Object].
Let’s see some examples.
<!DOCTYPE html>
<html>
<body>
<h2>Printing JavaScript Objects</h2>
<p>OUTPUT : [object Object]:</p> <p id="test"></p>
<button onclick="alert(person)">Show Alert</button> <script>
const person = { name: "Sam", country: "India" };
document.getElementById("test").innerHTML = person;
console.log('output' + person);
</script> </body>
</html>
If you run above example you will surely see [object, Object]
Everywhere.
That’s because the method/key we are invoking takes parameter as string and outputs string Ex: alert()
and innerHTML
.
In above console.log('output ' + person)
we are concatenating object with string, Hence results in string.
Now if want want original object to be displayed you can use JSON.stringify()
method. It will convert the object into a string format.
Like This
<!DOCTYPE html>
<html>
<body>
<h2>Printing JavaScript Objects</h2>
<p>OUTPUT : [object Object]:</p> <p id="test"></p>
<button onclick="alert(JSON.stringify(person))">
Show Alert
</button>
<script>
const person = { name: "Sam", country: "India" };
document.getElementById("test").innerHTML = JSON.stringify(person);
console.log('output' + JSON.stringify(person));
// OR
console.log('output', person); // Removed concatenation
</script></body>
</html>
And the output for the above code will be like this :
See? Working fine already.
I hope this article help you learn something new today.
Cheers!!