Start Coding

Topics

JavaScript Symbol

Introduced in ECMAScript 2015 (ES6), Symbol is a unique and immutable primitive data type in JavaScript. It serves as a guaranteed unique identifier, primarily used as object property keys.

What is a Symbol?

A Symbol is a primitive value that represents a unique identifier. Unlike strings or numbers, Symbols are always unique, even if they have the same description. This uniqueness makes them ideal for certain use cases in JavaScript programming.

Creating Symbols

To create a Symbol, use the Symbol() function:


const mySymbol = Symbol();
const namedSymbol = Symbol('description');
    

Note that Symbol() is a function, not a constructor. Using new Symbol() will result in a TypeError.

Use Cases for Symbols

1. Unique Object Properties

Symbols are often used as unique keys for object properties:


const uniqueKey = Symbol('myUniqueKey');
const obj = {
    [uniqueKey]: 'This property is accessed using a Symbol'
};

console.log(obj[uniqueKey]); // Output: This property is accessed using a Symbol
    

2. Avoiding Name Collisions

Symbols help prevent accidental property name conflicts in objects, especially useful when working with third-party code or libraries.

Symbol Properties and Methods

  • Symbol.for(key): Creates a Symbol in the global Symbol registry
  • Symbol.keyFor(sym): Retrieves a shared Symbol key from the global Symbol registry
  • Symbol.iterator: A well-known Symbol used to make objects iterable

Important Considerations

  • Symbols are not enumerable in for...in loops
  • Symbols are ignored by JSON.stringify()
  • Symbols can be used with Object.getOwnPropertySymbols() to retrieve all Symbol properties of an object

Example: Using Symbols for Private Properties

Symbols can be used to create "private" object properties:


const privateProperty = Symbol('privateProperty');

class MyClass {
    constructor() {
        this[privateProperty] = 'This is a private property';
    }

    getPrivateProperty() {
        return this[privateProperty];
    }
}

const instance = new MyClass();
console.log(instance.getPrivateProperty()); // Output: This is a private property
console.log(instance[privateProperty]); // Output: undefined (Symbol is not accessible directly)
    

Related Concepts

To deepen your understanding of JavaScript and how Symbols fit into the language, explore these related topics:

Symbols play a crucial role in modern JavaScript development, offering unique identifiers and enhancing object property management. As you continue to explore JavaScript Syntax and JavaScript Object Properties, keep Symbols in mind as a powerful tool for creating more robust and maintainable code.