Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The main reason why Symbols were added AFAIK is to specify protocols / interfaces. Right now, duck typing is all we have in JS.

How do you check if an object is a Promise? You do `(typeof obj.then === 'function')`. Is this good? No, not really, especially not when the language reserves such a word - the problem is that they're global names and can easily conflict with existing methods.

In contrast, a symbol is used for the Iterator protocol [1]. You implement the protocol by adding a method to your object at the key "Symbol.iterator" that returns an iterator object. Unlike with string keys, its impossible for someone to have already used Symbol.iterator as a key before: the value didn't exist at all. As a result, this feature lets ES.next and libraries define new protocols without the need to come up with unique method names that aren't used in any library.

[1]: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/T...



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: