The JavaScript ES6 introduced a new primitive data type called Symbol. Symbols are immutable (cannot be changed) and are unique. we use the Symbol() function to create a Symbol.
Syntax:
const message = Symbol('hello');
We can check type of symbol-function
const a = Symbol()
console.log(typeof a) //Output : "symbol"
For instance, here are two symbols with the same description – they are not equal:
let value1 = Symbol("message");
let value2 = Symbol("message");
console.log(value1 == value2); //Output : false
Though value1 and value2 both contain the same description, they are different.
Access Symbol Description
To access the description of a symbol, we use the. operator
const a = Symbol('hello');
console.log(a.description); // Output : “hello”
We can also use symbol as a key but it doesnt iterate in for loop.
let id = Symbol("id");
let person = {
name: "John",
age: 30,
[id]: 10
};
for (let key in person) {
console.log(key);
}
//Output :
"name"
"age"
Symbol Methods
There are various methods available with Symbol.
Method | Description |
for() | Searches for existing symbols |
keyFor() | It returns a shared symbol key from the global symbol registry. |
toSource() | It returns a string containing the source of the Symbol object |
valueOf() | It returns the primitive value of the Symbol object. |
keyFor()
It returns a key from the symbol.
// get symbol by name
let message = Symbol.for('hello');
let message1 = Symbol.for('world');
// get name by symbol
console.log( Symbol.keyFor(message) ); // Output : hello
console.log( Symbol.keyFor(message1) ); // Output : id
Symbol Properties
There are various properties available with Symbol.
Properties | Description |
description | Returns a string containing the description of the symbol |
iterator | Returns the default iterator for an object |
match | Matches against a string |
replace | Replaces matched substrings of a string |
search | Returns the index within a string that matches the regular expression |
split | Splits a string at the indices that match a regular expression |
species | Creates derived objects |
const message = Symbol('hello');
// description property
console.log(message.description); // Output : hello