Symbol Types

Symbol Types

Symbol Types in JavaScript

Symbols are a primitive data type introduced in ECMAScript 6 (ES6). A Symbol is a unique and immutable value that can be used as an identifier for object properties. Each Symbol is guaranteed to be unique, even if two symbols have the same description.

Symbols are especially useful when you want to create unique property keys that cannot be easily overwritten or accessed.

1️⃣ Creating Symbols

You can create a Symbol using the Symbol() function. The function can optionally accept a description (a string) that can be used for debugging, but it does not affect the uniqueness of the Symbol.

const symbol1 = Symbol(); const symbol2 = Symbol('description'); const symbol3 = Symbol('description'); console.log(symbol1); // Symbol() console.log(symbol2); // Symbol(description) console.log(symbol2 === symbol3); // false (Symbols are always unique)

Here:

  • symbol1 is created without a description.
  • symbol2 and symbol3 both have the description "description", but they are still distinct, unique values.

2️⃣ Use Case of Symbols

2.1 Unique Object Properties

One of the main use cases of Symbols is to create unique property keys in objects, ensuring there is no accidental overwriting of property names.

const sym1 = Symbol('name'); const sym2 = Symbol('name'); const obj = { [sym1]: 'John', [sym2]: 'Doe' }; console.log(obj[sym1]); // John console.log(obj[sym2]); // Doe console.log(sym1 === sym2); // false (they are different symbols)

Even though sym1 and sym2 have the same description, they are distinct, so their associated properties in the object don't clash.

2.2 Avoiding Property Clashes

Symbols provide a way to avoid property name conflicts when working with objects in large projects or third-party libraries.

3️⃣ Symbol.for() and Symbol.keyFor()

JavaScript provides two special methods, Symbol.for() and Symbol.keyFor(), which allows you to reuse symbols by registering them in a global symbol registry.

3.1 Symbol.for()

The Symbol.for() method looks up a symbol in the global symbol registry (if a symbol with the given description already exists). If not, it creates a new one.

const globalSymbol1 = Symbol.for('global'); const globalSymbol2 = Symbol.for('global'); console.log(globalSymbol1 === globalSymbol2); // true (the same symbol from the global registry)

In this case, globalSymbol1 and globalSymbol2 are the same symbol, because they both come from the global registry with the same description 'global'.

3.2 Symbol.keyFor()

The Symbol.keyFor() method allows you to retrieve the description of a symbol that was created using Symbol.for().

const globalSymbol = Symbol.for('global'); const description = Symbol.keyFor(globalSymbol); console.log(description); // 'global'
  • Note: Symbol.keyFor() only works for symbols created with Symbol.for(), not for those created using Symbol().

4️⃣ Well-known Symbols

JavaScript provides several built-in symbols, often referred to as well-known symbols, which are used for internal operations of JavaScript objects. These symbols allow you to hook into and customize the behavior of objects in different ways.

4.1 Symbol.iterator

The Symbol.iterator is used to define the default iterator for objects (e.g., arrays, sets, and maps). It allows objects to be iterated over in a for...of loop or other iterable contexts.

const obj = { [Symbol.iterator]: function* () { yield 1; yield 2; yield 3; } }; for (let value of obj) { console.log(value); // 1, 2, 3 }

Here, the Symbol.iterator method is defined for the object, which makes it iterable in a for...of loop.

4.2 Symbol.toPrimitive

The Symbol.toPrimitive symbol is used to define how an object is converted to a primitive value (e.g., when it's coerced to a string or a number).

const obj = { [Symbol.toPrimitive]: function(hint) { if (hint === 'string') return 'This is a string'; if (hint === 'number') return 123; return null; } }; console.log(String(obj)); // This is a string console.log(Number(obj)); // 123

Here, the Symbol.toPrimitive method customizes the conversion of the obj to a string or number.

4.3 Symbol.hasInstance

The Symbol.hasInstance symbol is used to define the behavior of the instanceof operator for an object.

class MyClass { static [Symbol.hasInstance](instance) { return instance.constructor === MyClass; } } console.log({} instanceof MyClass); // false console.log(new MyClass() instanceof MyClass); // true

By overriding Symbol.hasInstance, you can control the behavior of instanceof for your custom classes.

4.4 Symbol.toStringTag

The Symbol.toStringTag is used to customize the string representation of an object when it is logged (e.g., in Object.prototype.toString()).

const obj = { [Symbol.toStringTag]: 'MyCustomObject' }; console.log(Object.prototype.toString.call(obj)); // [object MyCustomObject]

5️⃣ Symbols and JSON

Symbols are not enumerable by default, so they are excluded from JSON.stringify().

const obj = { name: 'John', [Symbol('id')]: 123 }; console.log(JSON.stringify(obj)); // {"name":"John"}

In the example above, the symbol property ([Symbol('id')]) is not included in the JSON string, because symbols are not part of the object's enumerable properties.

6️⃣ Conclusion

Symbols are a powerful feature in JavaScript for creating unique property keys and avoiding name clashes, especially when working with third-party code or large applications. They are immutable and can be used for customizing the behavior of objects in a way that helps with encapsulation and modularity. Some common use cases include:

  • Creating unique property keys.
  • Using built-in well-known symbols for customizing object behavior.
  • Avoiding property name conflicts in large-scale applications.

Let me know if you need more examples or details on any specific aspect! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close