/

JavaScript Symbols: Explained and Utilized

JavaScript Symbols: Explained and Utilized

Symbols are a unique and powerful data type in JavaScript, introduced in ECMAScript 2015. Unlike other primitive data types like strings, numbers, booleans, null, and undefined, symbols have a distinct characteristic - their values are kept private and meant for internal use only. Once created, symbols are immutable and their values remain hidden, with only the symbol reference accessible.

To create a symbol, you can use the Symbol() global factory function. Each time this function is invoked, a new and unique symbol is generated, guaranteed to be different from any other symbol.

1
const mySymbol = Symbol();

You can also pass a parameter to the Symbol() function, which is used as the symbol’s description. This description is purely for debugging purposes.

1
2
console.log(Symbol()); // Symbol()
console.log(Symbol('Some Test')); // Symbol(Some Test)

Symbols are commonly used to identify object properties, particularly to avoid name clashes between properties. Since no symbol is equal to another, symbols can ensure that property names remain unique. Additionally, symbols can be used to add properties to an object that cannot be overwritten, either intentionally or unintentionally by the user.

Here are some examples of utilizing symbols in JavaScript:

1
2
3
4
5
6
7
8
9
10
const NAME = Symbol();
const person = {
[NAME]: 'Flavio'
};

person[NAME]; // 'Flavio'

const RUN = Symbol();
person[RUN] = () => 'Person is running';
console.log(person[RUN]()); // 'Person is running'

One crucial characteristic of symbols is that they are not enumerated. This means that symbols do not appear in for..of or for..in loops that iterate over an object’s properties. Symbols are also not included in the results of Object.keys() or Object.getOwnPropertyNames(). However, you can access all the symbols assigned to an object using the Object.getOwnPropertySymbols() method.

In conclusion, symbols in JavaScript provide a unique way to ensure property name uniqueness and create private and non-enumerable properties. They are a valuable addition to the language and can be used in various scenarios where property identification and protection are required.

tags: [“JavaScript”, “Symbols”, “Object Properties”, “ECMAScript 2015”]