DEV Community

Cover image for Exploring Symbols in JavaScript
Mainul Hasan
Mainul Hasan

Posted on • Updated on

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...

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Symbols are super useful! I use them regularly. My Metho library would not be possible without them. I also made use of Symbol.iterator to make a range syntax for numbers, which I later expanded into a library to add a range syntax to any object.

Collapse
 
mainulspace profile image
Mainul Hasan

That's awesome to hear! Symbols indeed offer a lot of flexibility and unique features in JavaScript. It sounds like you've done some innovative work with them, especially with your Metho library and expanding the range syntax. I'd love to check out your library and see how you've utilized Symbols. Thanks for sharing your experience, and keep up the great work! 🚀👍

Collapse
 
liftoffstudios profile image
Liftoff Studios

Great Article!
Never really heard or used Symbols in my projects though, so it's nice to know this existed Lol

Collapse
 
mainulspace profile image
Mainul Hasan

Thank you so much for the kind words! I'm glad I could introduce you to Symbols in JavaScript. They're not always commonly used in everyday projects, but they can be quite powerful in certain situations. I encourage you to play around with them and see how they might fit into your future work. Happy coding! 😊