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:
let uid = Symbol.for("uid");
let object = {
[uid]: "12345"
};
let symbols = Object.getOwnPropertySymbols(object);
console.log(symbols.length); // 1
console.log(symbols[0]); // "Symbol(uid)"
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.