VCF

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

The mix-upJavaScript
const order = { item: "latte", qty: 2 };
String(order);  // "[object Object]"
Everything inside is lost.
What worksJavaScript
JSON.stringify(order);  // '{"item":"latte","qty":2}'
Every key and value, as text.

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.

15 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.