ECMAScript 6+ (ES6+) – Using Symbols
ECMAScript 6, also known as ES6 or ES2015, introduced a new primitive data type called Symbols. Symbols are unique and immutable values that can be used as object property keys. They are often used to create private or protected properties in JavaScript objects. Let’s explore how Symbols can be used in ES6+.
Creating a Symbol is simple. You can use the Symbol() function to create a new Symbol:
const mySymbol = Symbol();
To give a Symbol a description (which is mainly for debugging purposes), you can pass a string parameter to the Symbol() function:
const mySymbol = Symbol('mySymbolDescription');
Symbols are guaranteed to be unique. Even if you create multiple Symbols with the same description, they are still different values:
const symbol1 = Symbol('mySymbol'); const symbol2 = Symbol('mySymbol'); console.log(symbol1 === symbol2); // false
One common use case for Symbols is to create private properties in objects. Let’s see an example of how Symbols can be used to create private properties in a class:
class MyClass { constructor() { this[Symbol('privateProperty')] = 'private value'; } getPrivateProperty() { return this[Symbol('privateProperty')]; } } const instance = new MyClass(); console.log(instance.getPrivateProperty()); // 'private value' console.log(instance[Symbol('privateProperty')]); // undefined
In the above example, we use a Symbol as the key for a private property in the class. This ensures that the private property is not accessible from outside the class.
Symbols can also be used to define well-known symbols, such as Symbol.iterator for custom iterable objects, Symbol.toStringTag for custom object string representations, and more.
Overall, Symbols in ECMAScript 6+ provide a powerful way to create unique and immutable values for object properties. They are particularly useful for creating private properties and defining well-known symbols in JavaScript.
For more information on Symbols in ECMAScript 6+, you can refer to the MDN web docs.