Exploring Symbols in JavaScript
Tags: javascript, webdev, programming, es6
Published: 2023-09-15 19:14:31

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.

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

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.

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

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

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.

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

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

## 4\. Global Symbol Registry

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

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

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

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.

{% twitter https://twitter.com/mainulspace/status/1699638679831036377?s=20 %}

## 5\. Reflecting on Symbols

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

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

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.

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

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

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**](https://twitter.com/mainulspace) and [**LinkedIn**](https://www.linkedin.com/in/mainulspace/). Let’s talk tech and coding!

## Read Next...
{% embed https://dev.to/mainulspace/short-circuit-evaluation-making-your-code-more-concise-2jne %}
{% embed https://dev.to/mainulspace/javascript-functional-programming-map-filter-reduce-5g55 %}
{% embed https://dev.to/mainulspace/essential-es6-features-for-mastering-react-4hlh %}