What is Object.getOwnPropertySymbols() in Javascript?

The Object.getOwnPropertySymbols() method is used to return all the symbols of an object. getOwnPropertySymbols() is declared as follows:

Object.getOwnPropertySymbols(obj)
  • obj: The object whose symbols are required.

Return value

The getOwnPropertySymbols() method returns an array that contains all the symbols of the object obj.

Note: If an object has no symbols, the getOwnPropertySymbols() method returns an empty array.

Browser compatibility

The getOwnPropertySymbols() method is supported by the following browsers:

  • Edge
  • Firefox
  • Google Chrome
  • Opera
  • Safari

Example

Consider the code snippet below, which demonstrates the use of the getOwnPropertySymbols() method:

var obj = {}
console.log("obj has symbols: ", Object.getOwnPropertySymbols(obj))
var symbol1 = Symbol('Local Symbol')
var symbol2 = Symbol.for('Global Symbol')
obj[symbol1] = 'symbol 1 assigned to abj1'
obj[symbol2] = 'symbol 2 assigned to abj2'
console.log("obj has symbols: ", Object.getOwnPropertySymbols(obj))

Explanation

An object obj is declared in line 1. Initially, obj has no symbol, which is why calling the getOwnPropertySymbols() method in line 3 returns an empty array. Two symbols, symbol1 and symbol2, are created in line 5 and line 6, respectively. These two symbols are then assigned to obj in lines 8-9. After assigning two symbols to obj, the getOwnPropertySymbols() method is called again in line 11. An array is returned, containing the symbols symbol1 and symbol2 of obj.

Copyright ©2024 Educative, Inc. All rights reserved