Retrieving Symbol Properties

The Object.keys() and Object.getOwnPropertyNames() methods can retrieve all property names in an object. The former method returns all enumerable property names, and the latter returns all properties regardless of enumerability. Neither method returns symbol properties, however, to preserve their ECMAScript 5 functionality. Instead, the Object.getOwnPropertySymbols() method was added in ECMAScript 6 to allow you to retrieve property symbols from an object.

The return value of Object.getOwnPropertySymbols() is an array of own property symbols. For example:

  1. let uid = Symbol.for("uid");
  2. let object = {
  3. [uid]: "12345"
  4. };
  5. let symbols = Object.getOwnPropertySymbols(object);
  6. console.log(symbols.length); // 1
  7. console.log(symbols[0]); // "Symbol(uid)"
  8. console.log(object[symbols[0]]); // "12345"

In this code, object has a single symbol property called uid. The array returned from Object.getOwnPropertySymbols() is an array containing just that symbol.

All objects start with zero own symbol properties, but objects can inherit symbol properties from their prototypes. ECMAScript 6 predefines several such properties, implemented using what are called well-known symbols.