Object.getOwnPropertySymbols()

Why Object.getOwnPropertySymbols ?

The Object.getOwnPropertySymbols () method returns all the symbol properties that are located on a particular object.

Returns the own symbol properties of an object. The own symbol properties of an object are those that are defined directly on that object, and are not inherited from the object’s prototype.

Syntax:

Object.getOwnPropertySymbols(object);

  • object (required):The object that contains the own symbols.
  • Return Value: An array that contains the own symbols of the object.

Note:You need to use Object.getOwnPropertySymbols to get the symbol properties of an object. Object.getOwnPropertyNames will not return the symbol properties.


JavaScript Object.getOwnPropertySymbols Examples

Example 1

        let myObj = {};
        let key = Symbol("description");

        myObj[key] = "data";

        let symbols = Object.getOwnPropertySymbols(myObj);

        console.log(symbols[0].toString())

output:

Symbol(description)


Example 2

        let myObj = {};
        num1 = Symbol(1);
        num2 = Symbol.for(2);

        let myObjSymbol = Object.getOwnPropertySymbols(myObj);
        console.log(myObjSymbol.length)

output:

0


Example 3

        let myObj = {};
        let first = Symbol("a");
        let second = Symbol.for("b");

        myObj[first] = "localSymbol";
        myObj[second] = "globalSymbol";

        let objSymbol = Object.getOwnPropertySymbols(myObj);

        console.log(objSymbol.length)

output:

2


Example 4

        let object1 = {};

        a = Symbol('a');
        b = Symbol.for('b');

        object1[a] = 'Alex';
        object1[b] = 'Rick';

        let objectSymbols = Object.getOwnPropertySymbols(object1);

        console.log(objectSymbols.length);

output:

2


Example 5

        let obj = {};
        let a = Symbol('a');
        let b = Symbol.for('b');

        obj[a] = 'localSymbol';
        obj[b] = 'globalSymbol';

        let objectSymbols = Object.getOwnPropertySymbols(obj);

        console.log(objectSymbols.length); 
        console.log(objectSymbols);       
        console.log(objectSymbols[0]);   

output:

2
[Symbol(a), Symbol(b)]
Symbol(a)


Sources:
developer.mozilla.org
www.javatpoint.com
technet.microsoft.com


Browser Support

Chrome38
Edgeyes
Firefox36
Internet ExplorerNo
Opera25
Safari9
Android webview38
Chrome for Android38
Edge mobileyes
Firefox for Android36
Opera Android25

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started