Explained: Symbol in Javascript with examples

Explained: Symbol in Javascript with examples

Symbol is a built-in object whose constructor returns a symbol primitive — also called a Symbol value or just a Symbol — that's guaranteed to be unique. Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak encapsulation, or a weak form of information hiding.

Example: Using Symbol as Unique Property Keys

javascript
Copy code
// Create unique symbols
const id = Symbol('id');
const name = Symbol('name');

// Create an object with symbol-based properties
const user = {
    [id]: 101,
    [name]: 'Alice',
    age: 25
};

// Access the symbol properties
console.log(user[id]); // 101
console.log(user[name]); // "Alice"

// Add another property using a symbol
const email = Symbol('email');
user[email] = 'alice@example.com';

console.log(user[email]); // "alice@example.com"

// Symbols are not enumerable in for...in loops or Object.keys
for (const key in user) {
    console.log(key); // Only "age" is logged
}

console.log(Object.keys(user)); // ["age"]

// You can still access all properties if you know the symbol keys
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id), Symbol(name), Symbol(email)]

Example: Using Symbol.iterator to Make an Object Iterable

javascript
Copy code
const collection = {
    items: ['apple', 'banana', 'cherry'],
    [Symbol.iterator]() {
        let index = 0;
        const items = this.items;
        return {
            next() {
                if (index < items.length) {
                    return { value: items[index++], done: false };
                } else {
                    return { done: true };
                }
            }
        };
    }
};

// Iterate over the object
for (const item of collection) {
    console.log(item);
}
// Output:
// apple
// banana
// cherry

This example shows how Symbol.iterator allows a custom object to be iterated using for...of.

Example: Using Symbol in a Popular npm Library

A notable example of Symbol usage is in the Express.js framework, a widely used web application framework for Node.js. In Express.js, Symbol is employed to define unique property keys, preventing potential conflicts with user-defined properties.

Code Snippet from Express.js:

javascript
Copy code
// In Express.js, a symbol is used to define a unique property key
const app = express();
app[Symbol('router')] = router;

In this snippet, Symbol('router') creates a unique symbol that serves as a property key for the app object. This approach ensures that the router property is distinct and does not interfere with other properties that might be added to the app object.

Benefits of Using Symbol in Libraries:

  • Uniqueness: Symbols guarantee that property keys are unique, reducing the risk of accidental overwrites.

  • Immutability: Once created, symbols cannot be changed, providing a stable identifier.

  • Non-enumerability: Properties keyed by symbols are not enumerable in loops, which can be beneficial for internal properties that should not be exposed.

Did you find this article valuable?

Support Coolhead by becoming a sponsor. Any amount is appreciated!