Table of contents
1.
Introduction
2.
Understanding the Symbol
2.1.
Using Symbols as Object Keys
2.2.
The Symbol.for and Symbol.keyFor Methods
3.
Symbol Properties
4.
Understanding Well-Known Symbols
5.
Examples of JavaScript Symbol
5.1.
Example: Creating a Symbol
5.2.
Example: Accessing Symbol Description
5.3.
Example: Each Symbol is Unique
6.
Frequently Asked Questions
6.1.
What is a Symbol in JavaScript?
6.2.
How do you create a Symbol?
6.3.
What is the use of Symbol.for and Symbol.keyFor methods?
7.
Conclusion
Last Updated: Jan 15, 2025
Easy

JavaScript Symbol

Author Gunjan Batra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

As JavaScript continues to evolve, it has been adding features that extend its capabilities. One such addition is the Symbol, a unique, immutable data type introduced in ECMAScript 2015. 

JavaScript Symbol

In this article, we will delve into the concept of the Symbol, including its creation, use cases, properties, and methods.

Understanding the Symbol

In JavaScript, a Symbol is a unique and immutable data type. When you create a Symbol, JavaScript ensures it's unique, even if two Symbols have the same description.

To create a Symbol, you use the Symbol() function. This function can accept an optional string parameter that represents the Symbol's description. However, this description doesn't impact the Symbol's uniqueness.


let symbol1 = Symbol();
let symbol2 = Symbol("symbol description");
let symbol3 = Symbol("symbol description");

Even though symbol2 and symbol3 have the same description, they are not the same.

Using Symbols as Object Keys

One of the main uses of Symbols is as keys in an object. Because every Symbol is unique, they allow us to create properties in objects that won't clash with any other property or method, thereby avoiding bugs that could arise from overwriting data.

let employee = {};
let id = Symbol('id');
employee[id] = 'E1001';

In the above code, the id Symbol is used as a property key in the employee object. The Symbol ensures the uniqueness of the property.

The Symbol.for and Symbol.keyFor Methods

JavaScript's Symbol object includes the Symbol.for(key) and Symbol.keyFor(sym) methods. The Symbol.for(key) method searches for existing Symbols with the given key and returns it if found. If not found, it creates a new Symbol with the given key.


let symbol1 = Symbol.for("employee");
let symbol2 = Symbol.for("employee");
console.log(symbol1 === symbol2);

/Outputs: 

True
Output

The Symbol.keyFor(sym) method returns a string representing the key for the Symbol sym in the global Symbol registry.

let symbol1 = Symbol.for("employee");
console.log(Symbol.keyFor(symbol1));   

Outputs:

"employee"
Output

Symbol Properties

Property NameDescription
Symbol.iteratorA built-in symbol that defines the default behavior for the iteration of objects (e.g., used in for...of loops).
Symbol.asyncIteratorA symbol used for asynchronous iteration, typically with for-await-of loops.
Symbol.hasInstanceAllows customization of the instanceof operator behavior.
Symbol.isConcatSpreadableDetermines if an object should be flattened when used with Array.prototype.concat.
Symbol.matchUsed by the String.prototype.match() method for pattern matching.
Symbol.replaceUsed by the String.prototype.replace() method to define a custom replacement operation.
Symbol.searchDefines the method used for the String.prototype.search() operation.
Symbol.splitDefines the method for splitting a string using String.prototype.split().
Symbol.toPrimitiveAllows the definition of a custom behavior for type conversion to primitive values.
Symbol.toStringTagUsed to customize the string representation of an object when calling Object.prototype.toString().
Symbol.unscopablesSpecifies the properties to be excluded from with statement scope.

Understanding Well-Known Symbols

JavaScript has some pre-defined Symbols known as well-known Symbols. These Symbols are used to represent internal language behaviors that were not previously exposed to developers. They include Symbol.iterator, Symbol.asyncIterator, Symbol.toStringTag, among others.

For instance, the Symbol.iterator is used by for...of loops to get the default iterator of an object.

let arr = [1, 2, 3];
let iterator = arr[Symbol.iterator]();
console.log(iterator.next());  

  Outputs:

Outputs

Examples of JavaScript Symbol

Example: Creating a Symbol

const mySymbol = Symbol('description');
console.log(mySymbol);  // Symbol(description)

 

Explanation:
A Symbol is created using the Symbol() function. It can optionally take a description as an argument, which is mainly for debugging purposes. The value itself is unique and immutable.

Example: Accessing Symbol Description

const mySymbol = Symbol('example');
console.log(mySymbol.description);  // "example"

 

Explanation:
The .description property of a Symbol returns the string description passed when creating the symbol. This helps in identifying the symbol but does not affect its uniqueness.

Example: Each Symbol is Unique

const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1 === symbol2);  // false

 

Explanation:
Symbols are guaranteed to be unique. Even if two symbols have the same description, they are not equal to each other. This uniqueness makes them useful for defining unique keys in objects without worrying about name conflicts.

Frequently Asked Questions

What is a Symbol in JavaScript?

A Symbol is a unique, immutable data type in JavaScript used mainly as object keys to avoid name clashes.

How do you create a Symbol?

You can create a Symbol using the Symbol() function.

What is the use of Symbol.for and Symbol.keyFor methods?

Symbol.for(key) searches for or creates a Symbol with the given key. Symbol.keyFor(sym) returns the key of a Symbol in the global registry.

Conclusion

Symbols in JavaScript, although a bit abstract, provide a powerful way to handle unique keys in objects, well-defined interfaces, and hidden implementation details. Understanding and using Symbols can unlock a new level of coding efficiency, leading to cleaner, safer, and bug-resistant code. As JavaScript continues to evolve, the Symbol will undoubtedly play a significant role in shaping the language.

To learn more about JavaScript, we recommend reading the following articles:

Live masterclass