Symbols

chloroplastic
Learning to code bit by bit
2 min readOct 10, 2018
Photo by Frankie Guarini on Unsplash

Symbols are primitive data types that can be created with the following syntax: let symbolName = Symbol("optionalDescription"); . A symbol can have a specific name, or description, which is used as a label. It’s important to note, though, that every symbol is almost always unique: two symbols with the same name are not necessarily equal to each other.

Because of that, symbols can be used in order to hide some properties of an object, in order to prevent other parts of your code from potentially accessing or modifying them. This is why for … in loops usually skip symbols.

If you need to have two equal symbols with the same description, and if you want to access them, you can use the global symbol registry: after creating a symbol in this registry, each name will correspond to a specific symbol. To read or return a symbol in the registry (or to create a new Symbol(key) in case it doesn’t exist yet) you can write: Symbol.for(key); . Once a symbol is in the registry it is called a global symbol, and it will have a global scope. The name of a global symbol can be returned with the syntax Symbol.keyFor(symbol); .

JS has many system symbols, that are accessible as Symbol.xxxx . These are often used to change some built-in behaviours.

TIL of the day:

  1. Symbols don’t auto-convert to strings.
  2. Garbage collector is a particular process in JS that automatically frees the memory by monitoring all objects and making sure that the unreachable ones are removed. An object, or even a collection of interlinked objects, is considered unreachable when there is no way to reference (access) it — in other words, when it gets unlinked from the root and becomes unusable. The only references that are considered in this process are those that make the object reachable: the incoming ones.

--

--