Unit 6 · JavaScript in the page
Why you see [object Object]
Turning an object into text with toString(), or by joining it to a string, gives "[object Object]" and loses everything inside. Use JSON.stringify(obj) to write it out, and JSON.parse(text) to turn it back into an object.
The mix-up
What people often think
“toString() turns an object into JSON.”
What the tutor says
toString() gives "[object Object]", which loses everything. JSON.stringify writes out every key and value.
How it works
Anything that leaves the page, such as a save to storage or a request to a server, travels as text. Saved data and server replies arrive as text too, so they need JSON.parse before you can use them as objects.
Side by side
const order = { item: "latte", qty: 2 };
String(order); // "[object Object]"JSON.stringify(order); // '{"item":"latte","qty":2}'Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Writing the object directly is the same fix.”
That avoids JSON instead of fixing it. Saved data and server replies arrive as text, so it has to parse.
Practise it with a tutor watching
JSON
Turn JSON text into objects and back, and spot JSON that will not parse.
Free, no account needed.