Unique Identifier
As per information provided by Mozilla Developer Network
Each call to Symbol() guarantees the return of a distinct Symbol. On the other hand, calling Symbol.for("key") will consistently return the same Symbol for a specific "key". When Symbol.for("key") is invoked, if an existing Symbol with the specified key exists in the global registry, that Symbol will be returned. Otherwise, a new Symbol is generated, added to the global registry under the given key, and then returned.
To put it simply, you can think of Symbol as similar to object[key] in Javascript.
Sometimes, we use keys in scenarios like this
const key = "keyname"
const object = {
[key]: "value"
}
We can now switch to using symbols instead
const symbol = Symbol.for('symbolname');
const object = {
[symbol]: "value" //the key is represented by a symbol
}
Additionally, one notable advantage of utilizing Symbols is that
Symbols used as keys will not be included when JSON.stringify() is employed:
This proves helpful when serializing JSON data while excluding specific fields within your code.
If you wish to delve deeper into some features of Symbols, I recommend reading this article
Getter Function (also known as get
)
Referencing once again the details from Mozilla Developer Network
The get syntax links an object property to a function that is triggered whenever that property is accessed.
But why would we require this functionality?
To illustrate, consider one of my favorite examples
class Person {
public firstName: string;
public lastName: string;
public fullName: string; //imagine assigning a value for `fullName` like this `${firstName} ${lastName}`?
}
The assignment of fullName
could become repetitive despite setting values for both firstName
and lastName
To address this issue, we introduce a getter function
class Person {
public firstName: string;
public lastName: string;
//introducing the getter!
public get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
Following this modification, you only need to assign values to firstName
and lastName
. Accessing person.fullName
will automatically populate the full name!
The question arises, "Can getters be used with Symbols?" The answer is affirmative!
By referring to the preceding documentation on getters, you'll come across this segment
const expr = 'foo';
const obj = {
get [expr]() { return 'bar'; }
};
console.log(obj.foo); // "bar"
In Conclusion
In response to your query
const symbol = Symbol.for('symbolname');
class Something {
public get [symbol]() {
return true;
}
}
This approach seems geared towards avoiding unintended data inclusion during JSON serialization via that getter function