”;
Introduction to Symbol
ES6 introduces a new primitive type called Symbol. They are helpful to implement metaprogramming in JavaScript programs.
Syntax
const mySymbol = Symbol() const mySymbol = Symbol(stringDescription)
A symbol is just a piece of memory in which you can store some data. Each symbol will point to a different memory location. Values returned by a Symbol() constructor are unique and immutable.
Example
Let us understand this through an example. Initially, we created two symbols without description followed by symbols with same description. In both the cases the equality operator will return false when the symbols are compared.
<script> const s1 = Symbol(); const s2 = Symbol(); console.log(typeof s1) console.log(s1===s2) const s3 = Symbol("hello");//description const s4 = Symbol("hello"); console.log(s3) console.log(s4) console.log(s3==s4) </script>
The output of the above code will be as mentioned below −
symbol false Symbol(hello) Symbol(hello) false
Sr.No | Property & Description |
---|---|
1 | Symbol.for(key)
searches for existing symbols in a symbol registry with the given key and returns it, if found. Otherwise, a new symbol gets created in the global symbol registry with this key.
|
2 | Symbol.keyFor(sym)
Retrieves a shared symbol key from the global symbol registry for the given symbol.
|
Symbol & Classes
A symbol can be used with classes to define the properties in the class. The advantage is that if property is a symbol as shown below, the property can be accessed outside the package only if the symbol name is known. So, data is much encapsulated when symbols are used as properties.
Example
<script> const COLOR = Symbol() const MODEL = Symbol() const MAKE = Symbol() class Bike { constructor(color ,make,model){ this[COLOR] = color; this[MAKE] = make; this[MODEL] = model; } } let bike = new Bike(''red'',''honda'',''cbr'') console.log(bike) //property can be accessed ony if symbol name is known console.log(bike[COLOR]) </script>
The output of the above code will be as stated below −
Bike {Symbol(): "red", Symbol(): "honda", Symbol(): "cbr"} red
”;