Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is Object.getOwnPropertySymbols() in Javascript?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

javascript

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring