Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 7

Object.getOwnPropertySymbols() Explained

This lesson is built with resources from youtube.com, developer.mozilla.org and 1 more site.

Hello! Welcome to our next lesson.

In our previous lessons, we've seen how well-known symbols like Symbol.hasInstance and Symbol.species act as powerful hooks, allowing us to customize core JavaScript behaviors. We noted that a key feature of symbols is that they don't show up in typical object property enumeration, which helps prevent accidental name collisions. This leads to a crucial question: if they're hidden from loops and Object.keys(), how do we find them when we need to?

This lesson directly answers that question. Your learning outcome is to: Retrieve all property symbols from an object using Object.getOwnPropertySymbols().

We'll cover:

  • Why standard methods like for...in and Object.keys() don't see symbol properties.
  • How to use Object.getOwnPropertySymbols() to get an array of all symbol keys on an object.
  • A comparative overview of all property traversal methods in ES6 to build a complete mental model.

1. The "Hidden" Nature of Symbol Properties

When symbols were introduced in ES6, they were designed to be a distinct category of property key. A major design goal was to prevent conflicts with existing and future string-based keys. For example, a library could add a symbol-keyed property to an object you provide without any risk of overwriting a property your code relies on, like id or name.

To achieve this separation, JavaScript engines exclude symbol properties from most legacy and standard iteration mechanisms.

Let's look at a concrete example.

const user = {
  id: 123,
  name: 'Satoshi',
  [Symbol('api_key')]: 'xyz-789-abc',
  [Symbol('session_id')]: 456
};

// Using for...in loop
console.log('--- for...in ---');
for (const key in user) {
  console.log(key); // only 'id', 'name'
}

// Using Object.keys()
console.log('\n--- Object.keys() ---');
console.log(Object.keys(user)); // ['id', 'name']

// Using Object.getOwnPropertyNames()
console.log('\n--- Object.getOwnPropertyNames() ---');
console.log(Object.getOwnPropertyNames(user)); // ['id', 'name']

As you can see, none of these common methods reveal the Symbol('api_key') or Symbol('session_id') properties. They are not private or truly inaccessible, but they are separate.

The following image provides a great visual summary of this behavior.

JavaScript Symbol Type and Object.getOwnPropertySymbols()
This image illustrates that symbols are unique identifiers used as object keys. It shows that standard `for...in` loops do not iterate over symbol properties and then introduces `Object.getOwnPropertySymbols()` as the method to retrieve them.

2. The Solution: Object.getOwnPropertySymbols()

To bridge this gap, ES6 introduced a specific method for this exact purpose: Object.getOwnPropertySymbols().

As its name implies, this static method on the Object constructor takes an object as an argument and returns an array containing all of that object's own (non-inherited) symbol-keyed properties.

The following short video clip demonstrates this perfectly.

The Complete Guide to JS Symbols ES6

Let's watch a quick demonstration from Colt Steele's guide on JS Symbols to see this method in action.

Watch from 05:58 to 06:29. The video shows how Object.getOwnPropertyNames() misses the symbol, while Object.getOwnPropertySymbols() successfully retrieves it.

Now, let's apply it to our user object from before:

const user = {
  id: 123,
  name: 'Satoshi',
  [Symbol('api_key')]: 'xyz-789-abc',
  [Symbol('session_id')]: 456
};

const symbolKeys = Object.getOwnPropertySymbols(user);
console.log(symbolKeys); // [Symbol(api_key), Symbol(session_id)]

// You can then use these symbols to access the values
console.log(user[symbolKeys[0]]); // 'xyz-789-abc'

This mechanism gives you the best of both worlds: symbols don't interfere with normal code, but when you need to perform metaprogramming or build inspection tools, you have a direct way to access them.


3. A Complete Map of Property Traversal

Object.getOwnPropertySymbols() is one piece of a larger puzzle. To have a robust understanding, it's helpful to compare all the available property traversal methods. This is analogous to having different introspection APIs in languages like Python (dir(), __dict__) that serve different purposes.

For a detailed breakdown, the "Exploring JS" book by Dr. Axel Rauschmayer offers an excellent overview.

14. New OOP features besides classes

Please read the following section from the 'Exploring JS' chapter on new OOP features. It provides a concise but comprehensive comparison of the five main ways to traverse properties in ES6.

Focus on the subsection titled 'Five operations that traverse properties'. Read the descriptions for each of the five bullet points to understand what keys (string/symbol), ownership (own/inherited), and enumerability each operation considers.

Here is a summary table based on that reading, which you can use as a quick reference:

Method / Operation Keys Ownership Enumerability
for...in loop String Own & Inherited Enumerable only
Object.keys() String Own only Enumerable only
Object.getOwnPropertyNames() String Own only All
Object.getOwnPropertySymbols() Symbol Own only All
Reflect.ownKeys() Both Own only All

As you can see, Reflect.ownKeys() is the most comprehensive, returning both string and symbol keys that are directly on the object. It's effectively a combination of Object.getOwnPropertyNames() and Object.getOwnPropertySymbols().

Test your understanding!

Imagine you are building a debugging utility. You are given an object that was created by a third-party library. This object has properties of several kinds:

  • Enumerable string keys
  • Non-enumerable string keys
  • Symbol keys
  • Inherited enumerable string keys

Your task is to write a function inspectObject(obj) that takes an object and returns a new object containing two arrays: ownStringKeys and ownSymbolKeys.

// Setup: Create a complex object for testing
const proto = {
  inheritedKey: 'I am inherited'
};

const myObject = Object.create(proto);

myObject.enumerableKey = 'I am visible';
myObject[Symbol('private_data')] = 12345;

Object.defineProperty(myObject, 'nonEnumerableKey', {
  value: 'I am hidden',
  enumerable: false
});

// Your function should go here
function inspectObject(obj) {
  // IMPLEMENT YOUR LOGIC HERE
}

const inspectionResult = inspectObject(myObject);
console.log(inspectionResult);
/*
Expected output:
{
  ownStringKeys: [ 'enumerableKey', 'nonEnumerableKey' ],
  ownSymbolKeys: [ Symbol(private_data) ]
}
*/

Hint: You'll need to use two different methods from the table above to get the desired result.

Show answer

You need to use Object.getOwnPropertyNames() to get all own string keys (both enumerable and non-enumerable) and Object.getOwnPropertySymbols() for the symbol keys.

// Setup: Create a complex object for testing
const proto = {
  inheritedKey: 'I am inherited'
};

const myObject = Object.create(proto);

myObject.enumerableKey = 'I am visible';
myObject[Symbol('private_data')] = 12345;

Object.defineProperty(myObject, 'nonEnumerableKey', {
  value: 'I am hidden',
  enumerable: false
});

function inspectObject(obj) {
  const ownStringKeys = Object.getOwnPropertyNames(obj);
  const ownSymbolKeys = Object.getOwnPropertySymbols(obj);

  return { ownStringKeys, ownSymbolKeys };
}

const inspectionResult = inspectObject(myObject);
console.log(inspectionResult);

Conclusion

Today we demystified how to access symbol-keyed properties. While they are intentionally kept separate from string-keyed properties to avoid collisions, they are by no means inaccessible.

Key Takeaways:

  • Standard property traversal methods like for...in, Object.keys(), and Object.getOwnPropertyNames() ignore symbol-keyed properties.
  • Object.getOwnPropertySymbols(obj) is the specific method designed to return an array of an object's own symbol properties.
  • For the most complete inspection of an object's own properties (both string and symbol), you can use Reflect.ownKeys(obj).

Next Up

This lesson concludes our initial exploration of creating, using, and finding symbols on objects. We will now wrap up this module by looking at our final well-known symbol: Symbol.match. In the next lesson, we will see how we can use this symbol to make our custom objects behave like regular expressions when used with string methods, allowing us to implement a custom pattern matching function.