JS: Object .getOwnPropertySymbols

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Object.getOwnPropertySymbols(obj)

Return all property keys whose key type is Symbol. (including non-enumerable keys)

return value type is Array.

const xx = Symbol("xx");
const jj = {};
jj[xx] = 3;

console.log(jj[xx] === 3);
// true

/* get all symbol key properties */
console.log(Object.getOwnPropertySymbols(jj));
// [ Symbol(xx) ]
// test Object.getOwnPropertySymbols(xobj) return all symbol keys including if it is non-enumerable

// create a symbol
const xsym = Symbol("xsym");

// create a object
const xobj = {};

// add the symbol key
Reflect.defineProperty(xobj, xsym, {
 value: 3,
 enumerable: false,
});

console.assert(xobj[xsym] === 3);

const all_sym_keys = Object.getOwnPropertySymbols(xobj);

console.assert(all_sym_keys.length === 1);
console.assert(all_sym_keys[0] === xsym);
// use Object.getOwnPropertySymbols() on Array.prototype
console.log(
 Object.getOwnPropertySymbols(Array.prototype),
);
// [ Symbol(Symbol.iterator), Symbol(Symbol.unscopables) ]