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:

  1. let firstName = Symbol("first name");
  2. // use a computed object literal property
  3. let person = {
  4. [firstName]: "Nicholas"
  5. };
  6. // make the property read only
  7. Object.defineProperty(person, firstName, { writable: false });
  8. let lastName = Symbol("last name");
  9. Object.defineProperties(person, {
  10. [lastName]: {
  11. value: "Zakas",
  12. writable: false
  13. }
  14. });
  15. console.log(person[firstName]); // "Nicholas"
  16. 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.