Posts

Showing posts from March, 2019

Symbol Type in Javascript

Symbol is a primitive type for unique identifiers. Symbols are created with Symbol() call with an optional description. Symbols are always different values, even if they have the same name. If we want same-named symbols to be equal, then we should use the global registry: Symbol.for(key) returns (creates if needed) a global symbol with key as the name. Multiple calls of Symbol.for return exactly the same symbol. Symbols have two main use cases: “Hidden” object properties. If we want to add a property into an object that “belongs” to another script or a library, we can create a symbol and use it as a property key. A symbolic property does not appear in for..in , so it won’t be occasionally listed. Also it won’t be accessed directly, because another script does not have our symbol, so it will not occasionally intervene into its actions. So we can “covertly” hide something into objects that we need, but others should not see, using symbolic properties. There