JavaScript Object.getOwnPropertySymbols()

The Object.getOwnPropertySymbols() method returns an array of all the symbol properties found in a given object.

Example

const symbol1 = Symbol('symbol1');
const symbol2 = Symbol('symbol2');

const obj = {
  property1: 'value1',
  [symbol1]: 'value2',
  [symbol2]: 'value3'
};

// get all the symbols of the obj const symbols = Object.getOwnPropertySymbols(obj);
console.log(symbols); // Output: [ Symbol(symbol1), Symbol(symbol2) ]

getOwnPropertySymbols() Syntax

The syntax of the getOwnPropertySymbols() method is:

Object.getOwnPropertySymbols(obj)

Here, getOwnPropertySymbols() is a static method. Hence, we need to access the method using the class name, Object.


getOwnPropertySymbols() Parameters

The getOwnPropertySymbols() method takes in:

  • obj - the object whose symbol properties are to be returned.

getOwnPropertySymbols() Return Value

The getOwnPropertySymbols() method returns an array of all symbol properties found in the given object.

Note: Object.getOwnPropertySymbols() returns all symbol properties of the object while Object.getOwnPropertyNames() returns the string properties.


Example: JavaScript Object.getOwnPropertySymbols()

// create a symbol id
let id = Symbol("id");

// create a symbol name
let name = Symbol("name");

// create an object with
// symbol keys: id and name
// and string key: age

let superhero1 = {
  [id]: 102,
  [name]: "Bruce Wayne",
  age: 40 
};

// get all symbols of superhero1 let objectSymbols = Object.getOwnPropertySymbols(superhero1);
// print the symbols console.log(objectSymbols); // Output: [ Symbol(id), Symbol(name) ]

In the above program, we have created an object superhero1 with the following properties:

  • symbols - id and name
  • string - age

Then, we used the getOwnPropertySymbols() method on superhero1 to list its symbol properties.

As expected, we get an array listing only the symbols id and name as the output.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges