Skip to main content

Welcome to a Grasp lesson

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

Lesson 1

Symbols as Unique Object Keys

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Hello! Welcome to your first lesson in the Advanced JavaScript course. I'm excited to embark on this journey with you to explore the deeper, more powerful features of the language.

Given your background in computer science and software engineering, you're in a great position to appreciate the "why" behind these advanced concepts, not just the "how." We'll be moving beyond syntax to understand the design patterns and architectural benefits these features provide.

This first module focuses on Symbols and Advanced Property Mechanics. We'll start with the foundational piece: the Symbol primitive. Today's lesson is designed to help you master the following outcome:

Create and use symbols as unique, non-enumerable property keys.

We will cover:

  • What a Symbol is and its guarantee of uniqueness.
  • How to use symbols to add properties to objects without the risk of name collisions.
  • The non-enumerable nature of symbol properties and what that means for object iteration and serialization.

Let's begin.

1. The Need for a Unique Identifier

In JavaScript, objects are dynamic collections of key-value pairs. Until ES6, property keys could only be strings. This presents a potential problem: property name collision.

Imagine you're writing a library that needs to add some metadata to objects it processes. If you choose a common property name like id or cacheKey, you risk overwriting an existing property on the user's object, or having your property overwritten by another library. This is where Symbol comes in.

Introduced in ES6, Symbol is a primitive data type, just like Number, String, or Boolean. Its sole purpose is to serve as a unique, immutable identifier.

To understand what a symbol is and why its uniqueness is so crucial, please read the introductory sections of this article from javascript.info.

Symbol type

This article provides a clear and concise introduction to the Symbol type. It explains what they are, how to create them, and why their uniqueness is a key feature.

Please read the sections 'Symbols' and 'Symbols don’t auto-convert to a string'. Focus on how symbols are created and the fact that even symbols with the same description are not equal.

As the article highlights, every call to Symbol() creates a new, unique value. The optional string you pass is just a description for debugging and has no bearing on the symbol's identity.

This image perfectly illustrates the core difference between strings and symbols:

JavaScript Symbol Uniqueness Comparison
This image compares string equality with symbol inequality. While two strings with the value 'id' are equal (`'id' === 'id'`), two symbols created with the description 'id' are not (`Symbol('id') !== Symbol('id')`), demonstrating the guaranteed uniqueness of each symbol.

2. Using Symbols as Object Property Keys

The primary use case for symbols is to be unique property keys. This allows you to "tag" objects with data or functionality, confident that you are not interfering with any other properties. Since your background involves AI/ML and data pipelines, you can think of this as a robust way to attach processing metadata to a data object without corrupting its original schema.

To see how this works in practice, watch the following video segment. It demonstrates how to create symbols and use them as object property keys to prevent conflicts.

JavaScript Symbols MasterClass // The Missing Guide

This clip from the 'JavaScript Symbols MasterClass' video by Basarat succinctly demonstrates how to use a symbol as an object key and why it prevents the conflicts that can occur with string-based keys.

Watch the section from 01:02 to 02:10. Pay close attention to the computed property syntax [mySymbol] used to assign a symbol as a key and how two different symbols with the same description can coexist on the same object.

As the video showed, when using a symbol as a property key in an object literal, you must use square brackets [] (computed property name syntax).

const id = Symbol('unique id');

const user = {
  name: 'John Doe',
  email: 'john.doe@example.com',
  [id]: 12345 // Using the symbol 'id' as a key
};

// To access the property, you must use the symbol itself
console.log(user[id]); // 12345

// Trying to access it like a string won't work
console.log(user.id); // undefined
console.log(user['id']); // undefined

This is how symbols solve the collision problem. Another piece of code, even another library, could define its own Symbol('unique id') and add it to the same user object without any conflict.

JavaScript Symbol as Property Keys Example
This code snippet shows how a symbol can be used as a key for both a data property (with a string value) and a method property on an object.

3. The "Non-Enumerable" Nature of Symbol Properties

A key characteristic of symbol-keyed properties is that they are non-enumerable in most common contexts. This means they are excluded from typical object iteration mechanisms. This isn't a security feature, but rather a way to prevent your symbolic properties from unexpectedly showing up or being processed by other code that isn't aware of them.

This provides a form of information hiding, ensuring that code looping over an object's keys won't stumble upon metadata it doesn't understand.

Let's see this in action. The next video segment clearly demonstrates which standard methods ignore symbol properties.

JavaScript Symbols MasterClass // The Missing Guide

This segment continues the 'JavaScript Symbols MasterClass' video, focusing on the concept of non-enumeration.

Watch from 02:10 to 03:23. Notice how methods like Object.keys(), the for...in loop, and JSON.stringify() all ignore the property keyed by a symbol.

Not Truly Private

It is crucial to understand that "non-enumerable" does not mean "private". The properties are hidden from common iteration, but they are not inaccessible. JavaScript provides a specific method to discover an object's symbol properties: Object.getOwnPropertySymbols().

const id = Symbol('id');
const user = {
  name: 'Alex',
  [id]: 'xyz-123'
};

// Standard methods ignore the symbol property
console.log(Object.keys(user)); // -> ['name']

// But it's discoverable if you know where to look
const symbols = Object.getOwnPropertySymbols(user);
console.log(symbols); // -> [Symbol(id)]

// And you can use the discovered symbol to get the value
console.log(user[symbols[0]]); // -> 'xyz-123'

If you need to get all own keys (both string and symbol), you can use Reflect.ownKeys(), a topic we will explore more in the metaprogramming module.

Test your understanding!

Consider the following code snippet. What will be logged to the console for each of the four console.log statements?

const metadataKey = Symbol('metadata');

const book = {
  title: 'The Three-Body Problem',
  author: 'Cixin Liu',
  [metadataKey]: {
    read: true,
    rating: 5
  }
};

// 1.
console.log(Object.keys(book));

// 2. 
console.log(JSON.stringify(book));

// 3.
for (const key in book) {
  console.log(`${key}: ${book[key]}`);
}

// 4.
const symbols = Object.getOwnPropertySymbols(book);
console.log(book[symbols[0]].rating);
Show answer
  1. ['title', 'author']

    • Object.keys() only returns own string-keyed, enumerable properties.
  2. {"title":"The Three-Body Problem","author":"Cixin Liu"}

    • JSON.stringify() only serializes string-keyed properties.
  3. title: The Three-Body Problem
    author: Cixin Liu

    • The for...in loop iterates over enumerable, string-keyed properties (including those from the prototype chain, though there are none here).
  4. 5

    • Object.getOwnPropertySymbols(book) returns an array [Symbol(metadata)]. We then access the first (and only) element of that array, symbols[0], and use it as a key to get the metadata object from book. Finally, we access the rating property of that metadata object.

4. A Note on Global Symbols: Symbol.for()

So far, we've focused on Symbol(), which guarantees a new, unique symbol on every call. There is another way to create symbols: Symbol.for(key).

Instead of creating a new symbol every time, Symbol.for(key) maintains a global registry of symbols.

  • When you call Symbol.for('myKey'), JavaScript first checks if a symbol with the key 'myKey' already exists in the registry.
  • If it does, it returns that same symbol.
  • If not, it creates a new symbol, adds it to the registry with the key 'myKey', and then returns it.

This means that Symbol.for('app.id') === Symbol.for('app.id') will always be true.

To clarify this important distinction, please read the following section. Although the article is about TypeScript, this part applies directly to JavaScript.

Understanding Symbols in TypeScript: A Deep Dive with ...

This article clearly lays out the differences between creating a unique local symbol and a shared global symbol.

Read the section titled 'Key Differences between Symbol() and Symbol.for()'. Focus on the concepts of uniqueness vs. a global registry and the different use cases for each.

For today's goal of creating unique property keys to prevent collisions when extending objects, Symbol() is the correct tool. Symbol.for() is used when you explicitly need to share a symbol across different parts of your application, like different modules or files.


Conclusion

In this lesson, we've taken our first step into advanced property mechanics in JavaScript. You now have a powerful tool for creating robust and non-conflicting object properties.

Key Takeaways:

  • Symbol is a primitive data type used to create unique identifiers. Every call to Symbol() produces a new, distinct value.
  • They are primarily used as object property keys to prevent name collisions, which is especially useful when adding metadata or functionality to objects you don't own.
  • To use a symbol as a key in an object literal, you must use the computed property syntax: const obj = { [mySymbol]: 'value' }.
  • By default, symbol-keyed properties are non-enumerable. They are ignored by for...in loops, Object.keys(), and JSON.stringify().
  • They are not truly private and can be accessed explicitly using Object.getOwnPropertySymbols(obj).

Next Up

We've seen that symbols provide a basic form of information hiding. In the next lesson, we will build upon this concept. We will learn how to implement private-like properties using symbols within closures, a classic JavaScript pattern for achieving stronger encapsulation.