Exploring Symbols in JavaScript

mainulspace

Mainul Hasan

Posted on September 15, 2023

Exploring Symbols in JavaScript

JavaScript keeps changing and adding new features. One cool update in ECMAScript 6, or ES6, is Symbols. Unlike other basic data types, you can’t change Symbols, and each one is unique. Let’s dive in and learn why Symbols are useful in JavaScript.

1. What is a Symbol?

In JavaScript, a Symbol is a unique and immutable primitive data type. We commonly use them as unique keys to prevent object properties from being clashed with or overwritten. This is super handy in complex projects and third-party libraries.



const specialSymbol = Symbol('description');
console.log(typeof specialSymbol);  // "symbol"


Enter fullscreen mode Exit fullscreen mode

The optional string description is solely for debugging purposes and does not affect the uniqueness of the Symbol.

2. Creating Symbols

You can create symbols by calling the Symbol() function. Every time you use this function, it generates a unique symbol.



const symbolA = Symbol('mySymbol');
const symbolB = Symbol('mySymbol');

console.log(symbolA === symbolB); // false


Enter fullscreen mode Exit fullscreen mode

Even though both symbols have the same description, they are distinct entities.

3. Symbols as Object Properties

One of the primary uses of Symbols is to serve as object keys, ensuring property uniqueness.



const uniqueLabel = Symbol('key');
const item = {
    [uniqueLabel]: 'Special value'
};

console.log(item[uniqueLabel]);  // "Special value"


Enter fullscreen mode Exit fullscreen mode

4. Global Symbol Registry

JavaScript offers a global symbol registry that also works in special contexts like iframes or service workers.



const globalSym = Symbol.for('universalSymbol');
const anotherGlobalSym = Symbol.for('universalSymbol');

console.log(globalSym === anotherGlobalSym); // Outputs: true


Enter fullscreen mode Exit fullscreen mode

The Symbol.for() method checks the global registry before creating a new symbol. If a symbol with the provided key exists, it returns that symbol. Otherwise, it creates a new one.

5. Reflecting on Symbols

To get the description of a symbol, you can use the description property:



const greetingSym = Symbol('hello');
console.log(greetingSym.description);  // Outputs: "hello"


Enter fullscreen mode Exit fullscreen mode

If you need to retrieve all symbol properties of an object, JavaScript provides Object.getOwnPropertySymbols():

6. Symbols and Iteration

When you loop through objects or convert them to JSON, the system automatically ignores these unique Symbol properties. This keeps them hidden and stops them from messing up common tasks.

7. Popular Symbols in JS

JavaScript also has built-in Symbols, often called ‘well-known symbols.’ For example, Symbol.iterator is a method that lets an object become iterable.



const numberSet = [1, 2, 3];
const numIterator = numberSet[Symbol.iterator]();

console.log(numIterator.next());  // Outputs: {value: 1, done: false}


Enter fullscreen mode Exit fullscreen mode

Other built-in Symbols like Symbol.match, Symbol.replace, and Symbol.search alter specific object behaviors.

Conclusion

Symbols in JavaScript help make unique keys, keep privacy, and work well with built-in features. You might not use them every day, but when you need them, they’re really helpful.

Understanding every detail of a feature is crucial for using it effectively. So, the next time you need a unique label or want to dig deeper into how JavaScript works, remember that Symbols are there to help.

I’d love to hear your insights! Drop a comment, and if you found it useful, a ❤️ or 🦄 would mean a lot. Sharing with your peers? Even better!

I’m active on Twitter and LinkedIn. Let’s talk tech and coding!

Read Next...

💖 💪 🙅 🚩
mainulspace
Mainul Hasan

Posted on September 15, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related