1

console.log(({
  title: "The Three Musketeers",
  author: "Alexandre Dumas",
  price: "$49"
}).toString());

It outputs an Object as [object Object], even though I am calling .toString() on it. Can anyone please explain why this happens?

3
  • What did you expect it to print and why did you expect that? Commented Sep 4, 2017 at 23:53
  • Your object does not have its own toString, so it uses the one from object. Commented Sep 4, 2017 at 23:57
  • Because that's what ECMA-262 says it should return. What did you expect? Commented Sep 5, 2017 at 0:02

5 Answers 5

1

Because for have built a JavaScript object that you are attempt to convert to a string. You are attempting to convert the entire object to a string, which can't (really) be done. As such, you simply get text that says "Hey, we've got an object here".

If however, you were to run .toString() on a property of that object (which is probably your intent), you would get a string representation of that property. This can be done by accessing the proeprty with the dot notation just before calling .toString(), as follows:

console.log(({
  title: "The Three Musketeers",
  author: "Alexandre Dumas",
  price: "$49"
}).title.toString());

Sign up to request clarification or add additional context in comments.

Comments

1

That's what happens when you try to convert or add an object to a string (which also tries to convert it to a string), what you're looking for is JSON.stringify(object) :

console.log(
    JSON.stringify(
        {title : "The Three Musketeers", author: "Alexandre Dumas", price: "$49"}
    )
);

Comments

0

If you're looking for a JSON string representation of the object, look into JSON.stringify()

Comments

0

If you do it this way it will work better

let object = {
  title: "The Three Musketeers",
  author: "Alexandre Dumas",
  price: "$49"
}
console.log("My object",object);

It's because it doesn't know how to render your object

Comments

0

The method you're looking for is JSON.stringify(). Try this:

JSON.stringify({
  title: "The Three Musketeers",
  author: "Alexandre Dumas",
  price: "$49"
}, null, 2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.