In JavaScript, encountering the output [object Object]
is common when attempting to display an object directly. This string is the default representation of an object, indicating that the object is of type Object
.
Why Does This Happen?
When you try to display an object using methods like alert()
or console.log()
, JavaScript implicitly calls the object’s toString()
method. For plain objects, the default toString()
method returns the string [object Object]
, which doesn’t provide detailed information about the object’s contents.
How to Display Object Contents
To view the actual properties of an object, you can convert it to a JSON string using JSON.stringify()
. This method serializes the object into a JSON-formatted string, making it easier to inspect its contents.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const student = { name: "John", school: "freeCodeCamp", }; // Attempting to alert the object directly alert(student); // Displays: [object Object] // Using JSON.stringify to display object contents alert(JSON.stringify(student)); // Displays: {"name":"John","school":"freeCodeCamp"} |
In the example above, JSON.stringify(student)
converts the student
object into a JSON string, allowing alert()
to display its properties and values.
Encountering [object Object]
is a normal aspect of JavaScript when dealing with objects. To effectively view an object’s contents, utilize JSON.stringify()
to convert the object into a readable string format.