Set#toString and Map#toString

C. Scott Ananian ecmascript at cscott.net
Thu Sep 4 14:51:10 PDT 2014


Neither `Set` nor `Map` have `toString` methods defined on the
prototype.  This can lead to somewhat surprising behavior for
interactive users (this is node with`es6-shim`):

```js
> s = new Set(['a'])
{}
> m = new Map([['a','b']])
{}
> s.toString()
'[object Object]'
> m.toString()
'[object Object]'
```

Eventually node's `util.inspect` (and the various browser analogs)
will presumably learn about `Map` and `Set`.  But the latest Chrome
beta still reports:
```js
> s = new Set(['a'])
< Set {}
> s.has('a')
< true
```

Since the potential for confusion with an empty object is clear, might
it make sense to define `Set#toString` and `Map#toString` methods in
ES6?  I'm thinking that:
```js
Set.prototype.toString = function() { return Array.from(this).toString(); }
```
Not sure about `Map#toString`, but the equivalent definition:
```js
Map.prototype.toString = function() { return Array.from(this).toString(); }
```
gives somewhat confusing results.  Eg:
```js
> (new Map([['k1','v1'],['k2','v2']])).toString()
'k1,v1,k2,v2'
```

What do y'all think?
 --scott


More information about the es-discuss mailing list