Symbol and Iterate Object in ES6
Write Ahead
ES6 introduces a new primitive type into JavaScript which is Symbol. All symbols are unique so you can treat them as tokens server as unique id.
You can create a symbol using its factory function Symbol(), you can pass a parameter to it as the name of the symbol, but most of time, the name is only used to debug, you can not access a symbol with name.
What Symbol can do
As property keys
As a primitive value, if we use typeof on a symbol, we get symbol. And also symbols can be used as property keys for constructing objects. So in ES6, for properties in objects, the definition changes to:
- Property keys are either strings or symbols;
- Property names are strings;
So we have a few new methods for objects and some changes on old methods.
1 | // from 2ality |
As unique constants
And since the symbols are all unique, so we can use symbols create a unique bindings, like this:
1 | const COLOR_RED = Symbol(); |
Now we have a binding that much powerful and strict than strings.
Symbol.iterator
Symbol.iterator is a special symbol that defines the iterator for your object. Currently some built-in types like Array, Map, Set, String and TypedArray have its default iteration behavior, but others don’t. So you can use Symbol.iterator define your own iterator for your object.
1 | let obj = { |
Retrieve the string from symbol
sometimes you will want to retrieve the string you pass to creating a symbol, you can use Symbol.for() and Symbol.keyFor().
1 | let sym = Symbol.for('Hello everybody!'); |
Summary
Symbol is a pretty cool stuff we have in ES6, you may come up with a lot of tricks and useful tips based on the unique of symbols.
Thanks for Symbols in ECMAScript 6 from ②ality – JavaScript and more and my favorite MDN.