menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:Symbols and unique object keys

menu

In JavaScript, symbols are a primitive data type introduced in ECMAScript 6 (ES6) that represents a unique and immutable value. They are often used as unique keys for object properties and offer several benefits, primarily for creating non-enumerable and non-overwritable properties.

Creating Symbols:

You can create a symbol using the Symbol() function. Symbols can have an optional description (useful for debugging and identifying them):

javascriptconst mySymbol = Symbol();
const anotherSymbol = Symbol('description');

Unique Object Keys:

Symbols are typically used as unique keys for object properties. They are different from string keys because they are not enumerable in for...in loops, and they do not clash with other properties, even if they have the same name.

javascriptconst mySymbol = Symbol('mySymbol');
const obj = {};

obj[mySymbol] = 'myValue';

console.log(obj[mySymbol]); // 'myValue'

// Symbols are not enumerated in for...in loops
for (const key in obj) {
  console.log(key); // No output since mySymbol is not enumerated
}

Use Cases for Symbols:

  1. Private Object Keys: Symbols can be used to create "private" properties for objects by using symbols as keys. These keys are inaccessible through standard object property access.

  2. Special Object Properties: Symbols are used by JavaScript itself to define special object properties (such as Symbol.iterator for defining iterables).

  3. Avoiding Property Name Collisions: Using symbols as property keys helps prevent naming collisions in objects.

Symbol Registry:

JavaScript has a global symbol registry that stores one symbol per key. Symbols created with the same description are guaranteed to be unique.

javascriptconst s1 = Symbol.for('mySymbol');
const s2 = Symbol.for('mySymbol');

console.log(s1 === s2); // true

Retrieving Symbol Keys:

You can retrieve symbol keys from objects using Object.getOwnPropertySymbols() or Reflect.ownKeys().

javascriptconst symbol1 = Symbol('symbol1');
const symbol2 = Symbol('symbol2');

const obj = {
  [symbol1]: 'value1',
  regularProperty: 'value2'
};

const symbols = Object.getOwnPropertySymbols(obj);
console.log(symbols); // [Symbol(symbol1)]

const allKeys = Reflect.ownKeys(obj);
console.log(allKeys); // [ 'regularProperty', Symbol(symbol1) ]

Conclusion:

Symbols in JavaScript are unique, immutable, and often used to define non-enumerable and non-overwritable properties in objects. They play a significant role in managing object properties, avoiding naming collisions, and creating private or special properties. They provide a way to create unique and non-conflicting keys for object properties, ensuring that properties are distinct and cannot be accidentally overwritten or misused.

1280 x 720 px