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.
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.
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:
We get a collection of property names when we clal Object.getOwnPropertyNames() . Symbols are not not part of that collection.
They do not get serialized when we use JSON.stringify on object that has Symbols as property keys.
Since we can not see symbol properties in for..in loop 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:
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.getOwnPropertySymbols to 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