ES6 Symbols, What They Are and How to Use Them
With ES6 ratification coming in June this year, now would be a great time to look at some of the new language features. Symbols are a lesser talked about new language primitive that underpins some of the new metaprogramming capabilities of ES6. This talk will give you a brief overview of what they are, and how they might affect your code.
To understand symbols you need to go back to basics of how objects work… and not work!
The ways js handles objects and strings can create unintended effects (presso shows example with values being overridden).
Symbols are a new primitive type – ie. Calling typeof will return “symbol”.
Symbols protect the values they contain and require you to access them via the symbol.
Use cases?
Because symbols are unique, there is no risk of collision. This makes them useful for storing state within web components; and can be used to make private values – that is, avoid polluting your public API. It is much like using jQuery’s .data but simpler.
ES6 has also defined built-in symbols. They allow you to hook into language features being exposed in ES6:
- for of loop (discrete from for in, doesn’t need to access index)
- symbol.iterator
- instanceof
- more to come as the language evolves
Biggest use case is encapsulation without (ab)using closures. The people consuming your code don’t necessarily want to see everything, you don’t want everything in your public API. To hack this, we have been closures to make things psuedo-private. That has lots of side effects – hard to unit test, hard to debug, bad for code re-use, small performance penalty.
Symbols solve encapsulation nicely, letting you set a const and refer to it via symbol. (see slide for pattern)
Browser support – great except for IE 🙁 Useful in io.js or node with the –harmony flag