Home > Mobile >  Difference between what's passed natively to console.log and toString
Difference between what's passed natively to console.log and toString

Time:03-18

In the following example:

let s = {x: 1, y: 1};
console.log(s, s.toString());
{ x: 1, y: 1 } [object Object]

Where is the '[object Object]' method defined? Why does printing an object evaluate to something different than doing object.toString() ?

CodePudding user response:

Various environments' consoles are generally intended for (and hence optimized for) debugging. If you log an object, the console is likely to show you a full, readable, interactive view of the object. The console does not convert logged values to strings before displaying them - that wouldn't be useful for debugging.

When an object has Object.prototype.toString called on it, it's required to go through these steps in the specification, which will result in [object SOMETHING] being logged, where SOMETHING may be Array, Function, etc, or Object if none of those special cases match. For a plain object, none of the special cases match, so you get [object Object].

CodePudding user response:

Replace s.string() with JSON.stringify()...

Refer here... What's the difference in using toString() compared to JSON.stringify()? for further

  • Related