0

In the following example:

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

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

CodeBug
  • 1,649
  • 1
  • 8
  • 23
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

0

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].

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-3

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

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

dinesh oz
  • 342
  • 1
  • 9