Post
JavaScript Symbols
JavaScript Symbols - Introduction
Symbol is a primitive data type in JavaScript. Symbols represent a way to define object keys that will never get in conflict with other keys.
Since they are one of the primitive data types they are immutable.
Their main purpose is to serve as an identifier for object’s properties.
Symbols as property names
Every time we get a value from Symbol() it will be unique one.
https://gist.github.com/Ibro/fd7dd40c8f13c6d95f12b4fbf0171f43
We get the following output:

As you can see, we used 2 symbols as properties, Hence, we have 2 different properties on obj object.
Lets see what happens if we use the same description and call the Symbol() method multiple times. For different variables or object properties we will still get a new and unique value. That’s because the value we pass to Symbol() function is a description not a unique name.
https://gist.github.com/Ibro/475d22fb7021f50bc96e2f4dee9434c3
Previous code produces following output:

Object members that have Symbols as keys will not be shown as being part of object when we loop them via for..in loop:
https://gist.github.com/Ibro/c9d50deba6a3161231bb933d7cc320bc
We get a collection of property names when we clal Object.getOwnPropertyNames() . Symbols are not not part of that collection.
https://gist.github.com/Ibro/be737b77b11f3d64c608ccb1382c3f08
They do not get serialized when we use JSON.stringify on object that has Symbols as property keys.
https://gist.github.com/Ibro/55e170e542a9e18bbd383f73c293e509
Since we can not see symbol properties in for..inloop nor we can use getOwnPropertyNames. Luckily we can use new method on Object called getOwnPropertySymbols. Similar to Object.getOwnPropertyNames(), you can get all symbol properties of a given object as an array of symbols:
https://gist.github.com/Ibro/63cd650d3c26b30d07eabf7443553547
Summary
Symbols:
- Are always unique
- Will (almost) never conflict with object’s property names
- We can not coerce them into primitives
- Will not appear in Object.getOwnPropertyNames keys collection
- Are not truly private
- We can use Object.getOwnPropertySymbolsto get list of symbols for a property
- Object members created with symbol as key will not appear when you use for..in loop
- They do not show in serialized object when using JSON.stringify