Using Symbols
You can use symbols anywhere you’d use a computed property name. You’ve already seen bracket notation used with symbols in this chapter, but you can use symbols in computed object literal property names as well as with Object.defineProperty()
and Object.defineProperties()
calls, such as:
let firstName = Symbol("first name");
// use a computed object literal property
let person = {
[firstName]: "Nicholas"
};
// make the property read only
Object.defineProperty(person, firstName, { writable: false });
let lastName = Symbol("last name");
Object.defineProperties(person, {
[lastName]: {
value: "Zakas",
writable: false
}
});
console.log(person[firstName]); // "Nicholas"
console.log(person[lastName]); // "Zakas"
This example first uses a computed object literal property to create the firstName
symbol property. The following line then sets the property to be read-only. Later, a read-only lastName
symbol property is created using the Object.defineProperties()
method. A computed object literal property is used once again, but this time, it’s part of the second argument to the Object.defineProperties()
call.
While symbols can be used in any place that computed property names are allowed, you’ll need to have a system for sharing these symbols between different pieces of code in order to use them effectively.