Object.getOwnPropertySymbols() method returns an array of all Symbol properties found directly upon a given object.
syntax ↴
Object.getOwnPropertySymbols(obj) ↴
obj The object whose Symbol properties are to be returned.
Object.getOwnPropertySymbols() returns an empty array [] if an object has no Symbols.
Symbol is a built-in object whose constructor returns a Symbol primitive - also called a Symbol value or just a Symbol - that's guaranteed to be unique.
Symbol.for creates a global, not-unique Symbol. It searches the Symbol registry for a Symbol associated with the given key and returns it if found. If that is not the case, it creates a new Symbol.
getOwnPropertySymbols works just like getOwnPropertyNames, except that instead of returning every property's name, it returns an array with the Symbols being used as keys.
Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object.
Every Symbol() call is guaranteed to return a unique Symbol. Every Symbol.for("key") call will always return the same Symbol for a given value of "key".
When Symbol.for("key") is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned.
Similar to Object.getOwnPropertyNames(), you can get all Symbol properties of a given object as an array of symbols.
Note that Object.getOwnPropertyNames() itself does not contain the symbol properties of an object and only the string properties.
// create an empty object | myObject
const myObject = {}
const a = Symbol.for("a")
const b = Symbol.for("b")
const c = Symbol.for("c")
const d = Symbol.for("d")
// assign values to each symbol
myObject[a] = "Apple"
myObject[b] = "Banana"
myObject[c] = "Mango"
myObject[d] = "Pear"
Object.getOwnPropertySymbols(myObject)