Symbol—A New Primitive Type
Explore the new primitive type of JavaScript, Symbol, and learn how it is used to hide properties.
We'll cover the following
JavaScript primitive types
JavaScript previously had five primitive types:
- number
- string
- Boolean
- null
- undefined
Now, it has one more type.
The motivation to bring Symbol
in ES6
Symbol
s can be used for three distinct purposes:
-
Hidden properties: To define properties for objects in such a way they don’t appear during normal iteration. These properties are not private; they’re just not easily discovered like other properties.
-
Global registry: To easily define a global registry or dictionary of objects.
-
Special well-known
Symbol
s: To define some special well-known methods in objects; this feature, which fills the void of interfaces, is arguably one of the most important purposes ofSymbol
.
Interfaces in languages like Java and C# are useful for design by contract and serve as a specification or a listing of abstract functions. When a function expects an interface, it is these languages guarantee that the object passed will conform to the interface’s specifications. However, there’s no such capability in JavaScript. You’ll see how Symbol
helps fill the gap.
Let’s explore each of the benefits one by one with examples.
Get hands-on with 1400+ tech skills courses.