ecma262 icon indicating copy to clipboard operation
ecma262 copied to clipboard

Object.prototype.toString()

Open timurtu opened this issue 10 years ago • 5 comments

The toString function on objects should return a JSON.stringify of the object.

const myObj = {a: 2}

console.log(myObj.toString()) // "[Object object]" // waste of time and energy ^

console.log(myObj.toString()) // "{ 'a': '2' }" // useful information ^

timurtu avatar Aug 17 '16 10:08 timurtu

This would break backwards compatibility.

mathiasbynens avatar Aug 17 '16 10:08 mathiasbynens

How?

timurtu avatar Aug 17 '16 10:08 timurtu

Lots of existing code relies on Object.prototype.toString.call(someObject) returning '[object Object]'. It’s commonly used to detect whether a given value is an object.

P.S. If you’re using console.log anyway, why bother with toString at all? console.log(myObj) gives you what you want.

mathiasbynens avatar Aug 17 '16 10:08 mathiasbynens

Okay I see your point but look how much more common this usage is. Doesn't it make more sense to return a string of the object with the toString method rather than a constant string saying what type of thing it is?

timurtu avatar Aug 17 '16 10:08 timurtu

It doesn’t matter if that makes more sense or not. We cannot break the web.

Anyway, this is not the place for such proposals. See https://github.com/tc39/ecma262/blob/master/CONTRIBUTING.md#proposals.

mathiasbynens avatar Aug 17 '16 10:08 mathiasbynens