Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Object getOwnPropertySymbols() Method

JavaScript Object getOwnPropertySymbols() Method

The Object.getOwnPropertySymbols() method in JavaScript is a standard built-in object which returns an array of all symbol properties that are present in a given object. An empty array is returned until symbol properties are set on the object.

Syntax: 

Object.getOwnPropertySymbols(obj)

Parameters: 

  • obj: This parameter is the object whose symbol properties are to be returned.

Return value: This method returns an array of all symbol properties that correspond to the properties found directly in the given object.

Below are some examples of this method 

Example 1: In this example, we will check for the symbol properties of the objects using the Object.getOwnPropertySymbols() Method in Javascript.

javascript




<script>
    const object1 = {};
    let vala = Symbol('geek1');
    let valb = Symbol.for('geek2');
      
    object1[vala] = 'localSymbol';
    object1[valb] = 'globalSymbol';
      
    const objectSymbols = Object.getOwnPropertySymbols(object1);
    console.log(objectSymbols.length);
      
    const object2 = {};  
    let a = Symbol('a');  
    let b = Symbol.for('b');  
    const objectSymbols1 = Object.getOwnPropertySymbols(object2);  
    console.log(objectSymbols1.length); 
</script>


Output: 

2
0

Example 2: In this example, we will check for the symbol properties of the objects using the Object.getOwnPropertySymbols() Method in Javascript.

javascript




<script>
    const object1 = {};
    let vala = Symbol('geek1');
    let valb = Symbol.for('geek2');
    let valc = Symbol.for('geek3');
      
    object1[vala] = 'localSymbol';
    object1[valb] = 'globalSymbol';
    object1[valc] = 'globalSymbol';
      
    const objectSymbols = Object.getOwnPropertySymbols(object1);
    console.log(objectSymbols.length);
    console.log(objectSymbols);      
    console.log(objectSymbols[0]);
    console.log(objectSymbols[2]);
    console.log(objectSymbols[1]);
</script>


Output: 

3
Array [Symbol(geek1), Symbol(geek2), Symbol(geek3)]
Symbol(geek1)
Symbol(geek3)
Symbol(geek2)

We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.

Supported Browsers: 

  • Google Chrome 38 and above
  • Edge 12 and above
  • Firefox 36 and above
  • Opera 25 and above
  • Safari 9 and above
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments